Moved checks for detail to home_server_ldb
[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 #ifdef HAVE_REGEX_H
36 #include <regex.h>
37
38 /*
39  *  For POSIX Regular expressions.
40  *  (0) Means no extended regular expressions.
41  *  REG_EXTENDED means use extended regular expressions.
42  */
43 #ifndef REG_EXTENDED
44 #define REG_EXTENDED (0)
45 #endif
46
47 #ifndef REG_NOSUB
48 #define REG_NOSUB (0)
49 #endif
50
51 #ifndef REG_ICASE
52 #define REG_ICASE (0)
53 #endif
54 #endif
55
56 static rbtree_t *realms_byname = NULL;
57
58 #ifdef HAVE_REGEX_H
59 typedef struct realm_regex_t {
60         REALM   *realm;
61         struct realm_regex_t *next;
62 } realm_regex_t;
63
64 static realm_regex_t *realms_regex = NULL;
65
66 #endif /* HAVE_REGEX_H */
67
68 typedef struct realm_config_t {
69         CONF_SECTION    *cs;
70         int             dead_time;
71         int             retry_count;
72         int             retry_delay;
73         int             fallback;
74         int             wake_all_if_all_dead;
75 } realm_config_t;
76
77 static realm_config_t *realm_config = NULL;
78
79 #ifdef WITH_PROXY
80 static rbtree_t *home_servers_byaddr = NULL;
81 static rbtree_t *home_servers_byname = NULL;
82 #ifdef WITH_STATS
83 static int home_server_max_number = 0;
84 static rbtree_t *home_servers_bynumber = NULL;
85 #endif
86
87 static rbtree_t *home_pools_byname = NULL;
88
89 /*
90  *  Map the proxy server configuration parameters to variables.
91  */
92 static const CONF_PARSER proxy_config[] = {
93         { "retry_delay",  PW_TYPE_INTEGER,
94           offsetof(realm_config_t, retry_delay),
95           NULL, Stringify(RETRY_DELAY) },
96
97         { "retry_count",  PW_TYPE_INTEGER,
98           offsetof(realm_config_t, retry_count),
99           NULL, Stringify(RETRY_COUNT) },
100
101         { "default_fallback", PW_TYPE_BOOLEAN,
102           offsetof(realm_config_t, fallback),
103           NULL, "no" },
104
105         { "dead_time",    PW_TYPE_INTEGER, 
106           offsetof(realm_config_t, dead_time),
107           NULL, Stringify(DEAD_TIME) },
108
109         { "wake_all_if_all_dead", PW_TYPE_BOOLEAN,
110           offsetof(realm_config_t, wake_all_if_all_dead),
111           NULL, "no" },
112
113         { NULL, -1, 0, NULL, NULL }
114 };
115 #endif
116
117 static int realm_name_cmp(const void *one, const void *two)
118 {
119         const REALM *a = one;
120         const REALM *b = two;
121
122         return strcasecmp(a->name, b->name);
123 }
124
125
126 #ifdef WITH_PROXY
127 static int home_server_name_cmp(const void *one, const void *two)
128 {
129         const home_server *a = one;
130         const home_server *b = two;
131
132         if (a->type < b->type) return -1;
133         if (a->type > b->type) return +1;
134
135         return strcasecmp(a->name, b->name);
136 }
137
138 static int home_server_addr_cmp(const void *one, const void *two)
139 {
140         const home_server *a = one;
141         const home_server *b = two;
142
143         if (a->server && !b->server) return -1;
144         if (!a->server && b->server) return +1;
145         if (a->server && b->server) {
146                 int rcode = a->type - b->type;
147                 if (rcode != 0) return rcode;
148                 return strcmp(a->server, b->server);
149         }
150
151         if (a->port < b->port) return -1;
152         if (a->port > b->port) return +1;
153
154         return fr_ipaddr_cmp(&a->ipaddr, &b->ipaddr);
155 }
156
157 #ifdef WITH_STATS
158 static int home_server_number_cmp(const void *one, const void *two)
159 {
160         const home_server *a = one;
161         const home_server *b = two;
162
163         return (a->number - b->number);
164 }
165 #endif
166
167 static int home_pool_name_cmp(const void *one, const void *two)
168 {
169         const home_pool_t *a = one;
170         const home_pool_t *b = two;
171
172         if (a->server_type < b->server_type) return -1;
173         if (a->server_type > b->server_type) return +1;
174
175         return strcasecmp(a->name, b->name);
176 }
177
178
179 /*
180  *      Xlat for %{home_server:foo}
181  */
182 static size_t xlat_home_server(UNUSED void *instance, REQUEST *request,
183                                char *fmt, char *out, size_t outlen,
184                                UNUSED RADIUS_ESCAPE_STRING func)
185 {
186         const char *value = NULL;
187         CONF_PAIR *cp;
188
189         if (!fmt || !out || (outlen < 1)) return 0;
190
191         if (!request || !request->home_server) {
192                 *out = '\0';
193                 return 0;
194         }
195
196         cp = cf_pair_find(request->home_server->cs, fmt);
197         if (!cp || !(value = cf_pair_value(cp))) {
198                 *out = '\0';
199                 return 0;
200         }
201         
202         strlcpy(out, value, outlen);
203
204         return strlen(out);
205 }
206
207
208 /*
209  *      Xlat for %{home_server_pool:foo}
210  */
211 static size_t xlat_server_pool(UNUSED void *instance, REQUEST *request,
212                                char *fmt, char *out, size_t outlen,
213                                UNUSED RADIUS_ESCAPE_STRING func)
214 {
215         const char *value = NULL;
216         CONF_PAIR *cp;
217
218         if (!fmt || !out || (outlen < 1)) return 0;
219
220         if (!request || !request->home_pool) {
221                 *out = '\0';
222                 return 0;
223         }
224
225         cp = cf_pair_find(request->home_pool->cs, fmt);
226         if (!cp || !(value = cf_pair_value(cp))) {
227                 *out = '\0';
228                 return 0;
229         }
230         
231         strlcpy(out, value, outlen);
232
233         return strlen(out);
234 }
235 #endif
236
237 void realms_free(void)
238 {
239 #ifdef WITH_PROXY
240 #ifdef WITH_STATS
241         rbtree_free(home_servers_bynumber);
242         home_servers_bynumber = NULL;
243 #endif
244
245         rbtree_free(home_servers_byname);
246         home_servers_byname = NULL;
247
248         rbtree_free(home_servers_byaddr);
249         home_servers_byaddr = NULL;
250
251         rbtree_free(home_pools_byname);
252         home_pools_byname = NULL;
253 #endif
254
255         rbtree_free(realms_byname);
256         realms_byname = NULL;
257
258 #ifdef HAVE_REGEX_H
259         if (realms_regex) {
260                 realm_regex_t *this, *next;
261
262                 for (this = realms_regex; this != NULL; this = next) {
263                         next = this->next;
264                         free(this->realm);
265                         free(this);
266                 }
267         }
268 #endif
269
270         free(realm_config);
271 }
272
273
274 #ifdef WITH_PROXY
275 static struct in_addr hs_ip4addr;
276 static struct in6_addr hs_ip6addr;
277 static char *hs_type = NULL;
278 static char *hs_check = NULL;
279 static char *hs_virtual_server = NULL;
280
281 static CONF_PARSER home_server_config[] = {
282         { "ipaddr",  PW_TYPE_IPADDR,
283           0, &hs_ip4addr,  NULL },
284         { "ipv6addr",  PW_TYPE_IPV6ADDR,
285           0, &hs_ip6addr, NULL },
286         { "virtual_server",  PW_TYPE_STRING_PTR,
287           0, &hs_virtual_server, NULL },
288
289         { "port", PW_TYPE_INTEGER,
290           offsetof(home_server,port), NULL,   "0" },
291
292         { "type",  PW_TYPE_STRING_PTR,
293           0, &hs_type, NULL },
294
295         { "secret",  PW_TYPE_STRING_PTR,
296           offsetof(home_server,secret), NULL,  NULL},
297
298         { "response_window", PW_TYPE_INTEGER,
299           offsetof(home_server,response_window), NULL,   "30" },
300         { "max_outstanding", PW_TYPE_INTEGER,
301           offsetof(home_server,max_outstanding), NULL,   "65536" },
302
303         { "zombie_period", PW_TYPE_INTEGER,
304           offsetof(home_server,zombie_period), NULL,   "40" },
305         { "status_check", PW_TYPE_STRING_PTR,
306           0, &hs_check,   "none" },
307         { "ping_check", PW_TYPE_STRING_PTR,
308           0, &hs_check,   NULL },
309
310         { "ping_interval", PW_TYPE_INTEGER,
311           offsetof(home_server,ping_interval), NULL,   "30" },
312         { "check_interval", PW_TYPE_INTEGER,
313           offsetof(home_server,ping_interval), NULL,   "30" },
314         { "num_answers_to_alive", PW_TYPE_INTEGER,
315           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
316         { "num_pings_to_alive", PW_TYPE_INTEGER,
317           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
318         { "revive_interval", PW_TYPE_INTEGER,
319           offsetof(home_server,revive_interval), NULL,   "300" },
320         { "status_check_timeout", PW_TYPE_INTEGER,
321           offsetof(home_server,ping_timeout), NULL,   "4" },
322
323         { "username",  PW_TYPE_STRING_PTR,
324           offsetof(home_server,ping_user_name), NULL,  NULL},
325         { "password",  PW_TYPE_STRING_PTR,
326           offsetof(home_server,ping_user_password), NULL,  NULL},
327
328 #ifdef WITH_STATS
329         { "historic_average_window", PW_TYPE_INTEGER,
330           offsetof(home_server,ema.window), NULL,  NULL },
331 #endif
332
333 #ifdef WITH_COA
334         { "irt",  PW_TYPE_INTEGER,
335           offsetof(home_server, coa_irt), 0, Stringify(2) },
336         { "mrt",  PW_TYPE_INTEGER,
337           offsetof(home_server, coa_mrt), 0, Stringify(16) },
338         { "mrc",  PW_TYPE_INTEGER,
339           offsetof(home_server, coa_mrc), 0, Stringify(5) },
340         { "mrd",  PW_TYPE_INTEGER,
341           offsetof(home_server, coa_mrd), 0, Stringify(30) },
342 #endif
343
344         { NULL, -1, 0, NULL, NULL }             /* end the list */
345 };
346
347
348 static int home_server_add(realm_config_t *rc, CONF_SECTION *cs, int pool_type)
349 {
350         const char *name2;
351         home_server *home;
352         int dual = FALSE;
353         CONF_PAIR *cp;
354
355         free(hs_virtual_server); /* used only for printing during parsing */
356         hs_virtual_server = NULL;
357
358         name2 = cf_section_name1(cs);
359         if (!name2 || (strcasecmp(name2, "home_server") != 0)) {
360                 cf_log_err(cf_sectiontoitem(cs),
361                            "Section is not a home_server.");
362                 return 0;
363         }
364
365         name2 = cf_section_name2(cs);
366         if (!name2) {
367                 cf_log_err(cf_sectiontoitem(cs),
368                            "Home server section is missing a name.");
369                 return 0;
370         }
371
372         home = rad_malloc(sizeof(*home));
373         memset(home, 0, sizeof(*home));
374
375         home->name = name2;
376         home->cs = cs;
377
378         memset(&hs_ip4addr, 0, sizeof(hs_ip4addr));
379         memset(&hs_ip6addr, 0, sizeof(hs_ip6addr));
380         if (cf_section_parse(cs, home, home_server_config) < 0) {
381                 free(home);
382                 return 0;
383         }
384
385         /*
386          *      Figure out which one to use.
387          */
388         if (cf_pair_find(cs, "ipaddr")) {
389                 home->ipaddr.af = AF_INET;
390                 home->ipaddr.ipaddr.ip4addr = hs_ip4addr;
391
392         } else if (cf_pair_find(cs, "ipv6addr")) {
393                 home->ipaddr.af = AF_INET6;
394                 home->ipaddr.ipaddr.ip6addr = hs_ip6addr;
395
396         } else if ((cp = cf_pair_find(cs, "virtual_server")) != NULL) {
397                 home->ipaddr.af = AF_UNSPEC;
398                 home->server = cf_pair_value(cp);
399                 if (!home->server) {
400                         cf_log_err(cf_sectiontoitem(cs),
401                                    "Invalid value for virtual_server");
402                         goto error;
403                 }
404
405                 if (!cf_section_sub_find_name2(rc->cs, "server", home->server)) {
406                   
407                         cf_log_err(cf_sectiontoitem(cs),
408                                    "No such server %s", home->server);
409                         goto error;
410                 }
411
412                 /*
413                  *      When CoA is used, the user has to specify the type
414                  *      of the home server, even when they point to
415                  *      virtual servers.
416                  */
417                 home->secret = strdup("");
418                 goto skip_port;
419
420         } else {
421                 cf_log_err(cf_sectiontoitem(cs),
422                            "No ipaddr, ipv6addr, or virtual_server defined for home server \"%s\".",
423                            name2);
424         error:
425                 free(home);
426                 free(hs_type);
427                 hs_type = NULL;
428                 free(hs_check);
429                 hs_check = NULL;
430                 return 0;
431         }
432
433         if (!home->port || (home->port > 65535)) {
434                 cf_log_err(cf_sectiontoitem(cs),
435                            "No port, or invalid port defined for home server %s.",
436                            name2);
437                 goto error;
438         }
439
440         if (0) {
441                 cf_log_err(cf_sectiontoitem(cs),
442                            "Fatal error!  Home server %s is ourselves!",
443                            name2);
444                 goto error;
445         }
446
447         if (!home->secret) {
448                 cf_log_err(cf_sectiontoitem(cs),
449                            "No shared secret defined for home server %s.",
450                            name2);
451                 goto error;
452         }
453
454         /*
455          *      Use a reasonable default.
456          */
457  skip_port:
458         if (!hs_type) hs_type = strdup("auth+acct");
459
460         if (strcasecmp(hs_type, "auth") == 0) {
461                 home->type = HOME_TYPE_AUTH;
462                 if (pool_type != home->type) {
463                 mismatch:
464                         cf_log_err(cf_sectiontoitem(cs),
465                                    "Server pool cannot include home server %s of type \"%s\"",
466                                    name2, hs_type);
467                         goto error;
468                 }
469
470         } else if (strcasecmp(hs_type, "acct") == 0) {
471                 home->type = HOME_TYPE_ACCT;
472                 if (pool_type != home->type) goto mismatch;
473
474         } else if (strcasecmp(hs_type, "auth+acct") == 0) {
475                 home->type = HOME_TYPE_AUTH;
476                 dual = TRUE;
477
478 #ifdef WITH_COA
479         } else if (strcasecmp(hs_type, "coa") == 0) {
480                 home->type = HOME_TYPE_COA;
481                 dual = FALSE;
482
483                 if (pool_type != home->type) goto mismatch;
484
485                 if (home->server != NULL) {
486                         cf_log_err(cf_sectiontoitem(cs),
487                                    "Home servers of type \"coa\" cannot point to a virtual server");
488                         goto error;
489                 }
490 #endif
491
492         } else {
493                 cf_log_err(cf_sectiontoitem(cs),
494                            "Invalid type \"%s\" for home server %s.",
495                            hs_type, name2);
496                 goto error;
497         }
498         free(hs_type);
499         hs_type = NULL;
500
501         if (!hs_check || (strcasecmp(hs_check, "none") == 0)) {
502                 home->ping_check = HOME_PING_CHECK_NONE;
503
504         } else if (strcasecmp(hs_check, "status-server") == 0) {
505                 home->ping_check = HOME_PING_CHECK_STATUS_SERVER;
506
507         } else if (strcasecmp(hs_check, "request") == 0) {
508                 home->ping_check = HOME_PING_CHECK_REQUEST;
509
510         } else {
511                 cf_log_err(cf_sectiontoitem(cs),
512                            "Invalid ping_check \"%s\" for home server %s.",
513                            hs_check, name2);
514                 goto error;
515         }
516         free(hs_check);
517         hs_check = NULL;
518
519         if ((home->ping_check != HOME_PING_CHECK_NONE) &&
520             (home->ping_check != HOME_PING_CHECK_STATUS_SERVER)) {
521                 if (!home->ping_user_name) {
522                         cf_log_err(cf_sectiontoitem(cs), "You must supply a user name to enable ping checks");
523                         goto error;
524                 }
525
526                 if ((home->type == HOME_TYPE_AUTH) &&
527                     !home->ping_user_password) {
528                         cf_log_err(cf_sectiontoitem(cs), "You must supply a password to enable ping checks");
529                         goto error;
530                 }
531         }
532
533         if ((home->ipaddr.af != AF_UNSPEC) && /* could be virtual server */
534             rbtree_finddata(home_servers_byaddr, home)) {
535                 cf_log_err(cf_sectiontoitem(cs), "Duplicate home server");
536                 goto error;
537         }
538
539         if (!rbtree_insert(home_servers_byname, home)) {
540                 cf_log_err(cf_sectiontoitem(cs),
541                            "Internal error %d adding home server %s.",
542                            __LINE__, name2);
543                 goto error;
544         }
545
546         if ((home->ipaddr.af != AF_UNSPEC) && /* could be virtual server */
547             !rbtree_insert(home_servers_byaddr, home)) {
548                 rbtree_deletebydata(home_servers_byname, home);
549                 cf_log_err(cf_sectiontoitem(cs),
550                            "Internal error %d adding home server %s.",
551                            __LINE__, name2);
552                 goto error;
553         }
554
555 #ifdef WITH_STATS
556         home->number = home_server_max_number++;
557         if (!rbtree_insert(home_servers_bynumber, home)) {
558                 rbtree_deletebydata(home_servers_byname, home);
559                 if (home->ipaddr.af != AF_UNSPEC) {
560                         rbtree_deletebydata(home_servers_byname, home);
561                 }
562                 cf_log_err(cf_sectiontoitem(cs),
563                            "Internal error %d adding home server %s.",
564                            __LINE__, name2);
565                 goto error;
566         }
567 #endif
568
569         if (home->response_window < 5) home->response_window = 5;
570         if (home->response_window > 60) home->response_window = 60;
571
572         if (home->max_outstanding < 8) home->max_outstanding = 8;
573         if (home->max_outstanding > 65536*16) home->max_outstanding = 65536*16;
574
575         if (home->ping_interval < 6) home->ping_interval = 6;
576         if (home->ping_interval > 120) home->ping_interval = 120;
577
578         if (home->zombie_period < 20) home->zombie_period = 20;
579         if (home->zombie_period > 120) home->zombie_period = 120;
580
581         if (home->zombie_period < home->response_window) {
582                 home->zombie_period = home->response_window;
583         }
584
585         if (home->num_pings_to_alive < 3) home->num_pings_to_alive = 3;
586         if (home->num_pings_to_alive > 10) home->num_pings_to_alive = 10;
587
588         if (home->ping_timeout < 3) home->ping_timeout = 3;
589         if (home->ping_timeout > 10) home->ping_timeout = 10;
590
591         if (home->revive_interval < 60) home->revive_interval = 60;
592         if (home->revive_interval > 3600) home->revive_interval = 3600;
593
594 #ifdef WITH_COA
595         if (home->coa_irt < 1) home->coa_irt = 1;
596         if (home->coa_irt > 5) home->coa_irt = 5;
597
598         if (home->coa_mrc < 0) home->coa_mrc = 0;
599         if (home->coa_mrc > 20 ) home->coa_mrc = 20;
600
601         if (home->coa_mrt < 0) home->coa_mrt = 0;
602         if (home->coa_mrt > 30 ) home->coa_mrt = 30;
603
604         if (home->coa_mrd < 5) home->coa_mrd = 5;
605         if (home->coa_mrd > 60 ) home->coa_mrd = 60;
606 #endif
607
608         if (dual) {
609                 home_server *home2 = rad_malloc(sizeof(*home2));
610
611                 memcpy(home2, home, sizeof(*home2));
612
613                 home2->type = HOME_TYPE_ACCT;
614                 home2->port++;
615                 home2->ping_user_password = NULL;
616                 home2->cs = cs;
617
618                 if (!rbtree_insert(home_servers_byname, home2)) {
619                         cf_log_err(cf_sectiontoitem(cs),
620                                    "Internal error %d adding home server %s.",
621                                    __LINE__, name2);
622                         free(home2);
623                         return 0;
624                 }
625                 
626                 if ((home->ipaddr.af != AF_UNSPEC) &&
627                     !rbtree_insert(home_servers_byaddr, home2)) {
628                         rbtree_deletebydata(home_servers_byname, home2);
629                         cf_log_err(cf_sectiontoitem(cs),
630                                    "Internal error %d adding home server %s.",
631                                    __LINE__, name2);
632                         free(home2);
633                         return 0;
634                 }
635
636 #ifdef WITH_STATS
637                 home2->number = home_server_max_number++;
638                 if (!rbtree_insert(home_servers_bynumber, home2)) {
639                         rbtree_deletebydata(home_servers_byname, home2);
640                         if (home2->ipaddr.af != AF_UNSPEC) {
641                                 rbtree_deletebydata(home_servers_byname, home2);
642                         }
643                         cf_log_err(cf_sectiontoitem(cs),
644                                    "Internal error %d adding home server %s.",
645                                    __LINE__, name2);
646                         free(home2);
647                         return 0;
648                 }
649 #endif
650         }
651
652         return 1;
653 }
654
655
656 static home_pool_t *server_pool_alloc(const char *name, home_pool_type_t type,
657                                       int server_type, int num_home_servers)
658 {
659         home_pool_t *pool;
660
661         pool = rad_malloc(sizeof(*pool) + (sizeof(pool->servers[0]) *
662                                            num_home_servers));
663         if (!pool) return NULL; /* just for pairanoia */
664         
665         memset(pool, 0, sizeof(*pool) + (sizeof(pool->servers[0]) *
666                                          num_home_servers));
667
668         pool->name = name;
669         pool->type = type;
670         pool->server_type = server_type;
671         pool->num_home_servers = num_home_servers;
672
673         return pool;
674 }
675
676 static int pool_check_home_server(realm_config_t *rc, CONF_PAIR *cp,
677                                   const char *name, int server_type,
678                                   home_server **phome)
679 {
680         home_server myhome, *home;
681         CONF_SECTION *server_cs;
682
683         if (!name) {
684                 cf_log_err(cf_pairtoitem(cp),
685                            "No value given for home_server.");
686                 return 0;
687         }
688
689         myhome.name = name;
690         myhome.type = server_type;
691         home = rbtree_finddata(home_servers_byname, &myhome);
692         if (home) {
693                 *phome = home;
694                 return 1;
695         }
696         
697         server_cs = cf_section_sub_find_name2(rc->cs, "home_server", name);
698         if (!server_cs) {
699                 cf_log_err(cf_pairtoitem(cp),
700                            "Unknown home_server \"%s\".", name);
701                 return 0;
702         }
703         
704         if (!home_server_add(rc, server_cs, server_type)) {
705                 return 0;
706         }
707         
708         home = rbtree_finddata(home_servers_byname, &myhome);
709         if (!home) {
710                 return 0;
711         }
712
713         *phome = home;
714         return 1;
715 }
716
717
718 static int server_pool_add(realm_config_t *rc,
719                            CONF_SECTION *cs, int server_type, int do_print)
720 {
721         const char *name2;
722         home_pool_t *pool = NULL;
723         const char *value;
724         CONF_PAIR *cp;
725         int num_home_servers;
726         home_server *home;
727
728         name2 = cf_section_name1(cs);
729         if (!name2 || ((strcasecmp(name2, "server_pool") != 0) &&
730                        (strcasecmp(name2, "home_server_pool") != 0))) {
731                 cf_log_err(cf_sectiontoitem(cs),
732                            "Section is not a home_server_pool.");
733                 return 0;
734         }
735
736         name2 = cf_section_name2(cs);
737         if (!name2) {
738                 cf_log_err(cf_sectiontoitem(cs),
739                            "Server pool section is missing a name.");
740                 return 0;
741         }
742
743         /*
744          *      Count the home servers and initalize them.
745          */
746         num_home_servers = 0;
747         for (cp = cf_pair_find(cs, "home_server");
748              cp != NULL;
749              cp = cf_pair_find_next(cs, cp, "home_server")) {
750                 num_home_servers++;
751
752                 if (!pool_check_home_server(rc, cp, cf_pair_value(cp),
753                                             server_type, &home)) {
754                                             
755                         return 0;
756                 }
757         }
758
759         if (num_home_servers == 0) {
760                 cf_log_err(cf_sectiontoitem(cs),
761                            "No home servers defined in pool %s",
762                            name2);
763                 goto error;
764         }
765
766         pool = server_pool_alloc(name2, HOME_POOL_FAIL_OVER, server_type,
767                                  num_home_servers);
768         pool->cs = cs;
769
770
771         /*
772          *      Fallback servers must be defined, and must be
773          *      virtual servers.
774          */
775         cp = cf_pair_find(cs, "fallback");
776         if (cp) {
777 #ifdef WITH_COA
778                 if (server_type == HOME_TYPE_COA) {
779                         cf_log_err(cf_sectiontoitem(cs), "Home server pools of type \"coa\" cannot have a fallback virtual server.");
780                         goto error;
781                 }
782 #endif
783
784                 if (!pool_check_home_server(rc, cp, cf_pair_value(cp),
785                                             server_type, &pool->fallback)) {
786                         
787                         goto error;
788                 }
789
790                 if (!pool->fallback->server) {
791                         cf_log_err(cf_sectiontoitem(cs), "Fallback home_server %s does NOT contain a virtual_server directive.", pool->fallback->name);
792                         goto error;
793                 }
794         }
795
796         if (do_print) cf_log_info(cs, " home_server_pool %s {", name2);
797
798         cp = cf_pair_find(cs, "type");
799         if (cp) {
800                 static FR_NAME_NUMBER pool_types[] = {
801                         { "load-balance", HOME_POOL_LOAD_BALANCE },
802                         { "fail-over", HOME_POOL_FAIL_OVER },
803                         { "round_robin", HOME_POOL_LOAD_BALANCE },
804                         { "fail_over", HOME_POOL_FAIL_OVER },
805                         { "client-balance", HOME_POOL_CLIENT_BALANCE },
806                         { "client-port-balance", HOME_POOL_CLIENT_PORT_BALANCE },
807                         { "keyed-balance", HOME_POOL_KEYED_BALANCE },
808                         { NULL, 0 }
809                 };
810
811                 value = cf_pair_value(cp);
812                 if (!value) {
813                         cf_log_err(cf_pairtoitem(cp),
814                                    "No value given for type.");
815                         goto error;
816                 }
817
818                 pool->type = fr_str2int(pool_types, value, 0);
819                 if (!pool->type) {
820                         cf_log_err(cf_pairtoitem(cp),
821                                    "Unknown type \"%s\".",
822                                    value);
823                         goto error;
824                 }
825
826                 if (do_print) cf_log_info(cs, "\ttype = %s", value);
827         }
828
829         cp = cf_pair_find(cs, "virtual_server");
830         if (cp) {
831                 pool->virtual_server = cf_pair_value(cp);               
832                 if (!pool->virtual_server) {
833                         cf_log_err(cf_pairtoitem(cp), "No value given for virtual_server");
834                         goto error;
835                 }
836
837                 if (do_print) {
838                         cf_log_info(cs, "\tvirtual_server = %s", pool->virtual_server);
839                 }
840
841                 if (!cf_section_sub_find_name2(rc->cs, "server",
842                                                pool->virtual_server)) {
843                         cf_log_err(cf_pairtoitem(cp), "No such server %s",
844                                    pool->virtual_server);
845                         goto error;
846                 }
847
848         }
849
850         num_home_servers = 0;
851         for (cp = cf_pair_find(cs, "home_server");
852              cp != NULL;
853              cp = cf_pair_find_next(cs, cp, "home_server")) {
854                 home_server myhome;
855
856                 value = cf_pair_value(cp);
857
858                 memset(&myhome, 0, sizeof(&myhome));
859                 myhome.name = value;
860                 myhome.type = server_type;
861
862                 home = rbtree_finddata(home_servers_byname, &myhome);
863                 if (!home) {
864                         DEBUG2("Internal sanity check failed");
865                         goto error;
866                 }
867
868                 if (0) {
869                         DEBUG2("Warning: Duplicate home server %s in server pool %s", home->name, pool->name);
870                         continue;
871                 }
872
873                 if (do_print) cf_log_info(cs, "\thome_server = %s", home->name);
874                 pool->servers[num_home_servers++] = home;
875         } /* loop over home_server's */
876
877         if (pool->fallback && do_print) {
878                 cf_log_info(cs, "\tfallback = %s", pool->fallback->name);
879         }
880
881         if (!rbtree_insert(home_pools_byname, pool)) {
882                 rad_assert("Internal sanity check failed");
883                 goto error;
884         }
885
886         if (do_print) cf_log_info(cs, " }");
887
888         cf_data_add(cs, "home_server_pool", pool, NULL);
889
890         rad_assert(pool->server_type != 0);
891
892         return 1;
893
894  error:
895         if (do_print) cf_log_info(cs, " }");
896         free(pool);
897         return 0;
898 }
899 #endif
900
901 static int old_server_add(realm_config_t *rc, CONF_SECTION *cs,
902                           const char *realm,
903                           const char *name, const char *secret,
904                           home_pool_type_t ldflag, home_pool_t **pool_p,
905                           int type, const char *server)
906 {
907 #ifdef WITH_PROXY
908         int i, insert_point, num_home_servers;
909         home_server myhome, *home;
910         home_pool_t mypool, *pool;
911         CONF_SECTION *subcs;
912 #else
913         rc = rc;                /* -Wunused */
914         realm = realm;
915         secret = secret;
916         ldflag = ldflag;
917         type = type;
918         server = server;
919 #endif
920
921         /*
922          *      LOCAL realms get sanity checked, and nothing else happens.
923          */
924         if (strcmp(name, "LOCAL") == 0) {
925                 if (*pool_p) {
926                         cf_log_err(cf_sectiontoitem(cs), "Realm \"%s\" cannot be both LOCAL and remote", name);
927                         return 0;
928                 }
929                 return 1;
930         }
931
932 #ifndef WITH_PROXY
933         return 0;               /* Not proxying.  Can't do non-LOCAL realms */
934
935 #else
936         mypool.name = realm;
937         mypool.server_type = type;
938         pool = rbtree_finddata(home_pools_byname, &mypool);
939         if (pool) {
940                 if (pool->type != ldflag) {
941                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent ldflag for server pool \"%s\"", name);
942                         return 0;
943                 }
944
945                 if (pool->server_type != type) {
946                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent home server type for server pool \"%s\"", name);
947                         return 0;
948                 }
949         }
950
951         myhome.name = name;
952         myhome.type = type;
953         home = rbtree_finddata(home_servers_byname, &myhome);
954         if (home) {
955                 if (secret && (strcmp(home->secret, secret) != 0)) {
956                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent shared secret for home server \"%s\"", name);
957                         return 0;
958                 }
959
960                 if (home->type != type) {
961                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent type for home server \"%s\"", name);
962                         return 0;
963                 }
964
965                 /*
966                  *      See if the home server is already listed
967                  *      in the pool.  If so, do nothing else.
968                  */
969                 if (pool) for (i = 0; i < pool->num_home_servers; i++) {
970                         if (pool->servers[i] == home) {
971                                 return 1;
972                         }
973                 }
974         }
975
976         /*
977          *      If we do have a pool, check that there is room to
978          *      insert the home server we've found, or the one that we
979          *      create here.
980          *
981          *      Note that we insert it into the LAST available
982          *      position, in order to maintain the same order as in
983          *      the configuration files.
984          */
985         insert_point = -1;
986         if (pool) {
987                 for (i = pool->num_home_servers - 1; i >= 0; i--) {
988                         if (pool->servers[i]) break;
989
990                         if (!pool->servers[i]) {
991                                 insert_point = i;
992                         }
993                 }
994
995                 if (insert_point < 0) {
996                         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);
997                         return 0;
998                 }
999         }
1000
1001         /*
1002          *      No home server, allocate one.
1003          */
1004         if (!home) {
1005                 const char *p;
1006                 char *q;
1007
1008                 home = rad_malloc(sizeof(*home));
1009                 memset(home, 0, sizeof(*home));
1010
1011                 home->name = name;
1012                 home->hostname = name;
1013                 home->type = type;
1014                 home->secret = secret;
1015                 home->cs = cs;
1016
1017                 p = strchr(name, ':');
1018                 if (!p) {
1019                         if (type == HOME_TYPE_AUTH) {
1020                                 home->port = PW_AUTH_UDP_PORT;
1021                         } else {
1022                                 home->port = PW_ACCT_UDP_PORT;
1023                         }
1024
1025                         p = name;
1026                         q = NULL;
1027
1028                 } else if (p == name) {
1029                                 cf_log_err(cf_sectiontoitem(cs),
1030                                            "Invalid hostname %s.",
1031                                            name);
1032                                 free(home);
1033                                 return 0;
1034
1035                 } else {
1036                         home->port = atoi(p + 1);
1037                         if ((home->port == 0) || (home->port > 65535)) {
1038                                 cf_log_err(cf_sectiontoitem(cs),
1039                                            "Invalid port %s.",
1040                                            p + 1);
1041                                 free(home);
1042                                 return 0;
1043                         }
1044
1045                         q = rad_malloc((p - name) + 1);
1046                         memcpy(q, name, (p - name));
1047                         q[p - name] = '\0';
1048                         p = q;
1049                 }
1050
1051                 if (!server) {
1052                         if (ip_hton(p, AF_UNSPEC, &home->ipaddr) < 0) {
1053                                 cf_log_err(cf_sectiontoitem(cs),
1054                                            "Failed looking up hostname %s.",
1055                                            p);
1056                                 free(home);
1057                                 free(q);
1058                                 return 0;
1059                         }
1060                 } else {
1061                         home->ipaddr.af = AF_UNSPEC;
1062                         home->server = server;
1063                 }
1064                 free(q);
1065
1066                 /*
1067                  *      Use the old-style configuration.
1068                  */
1069                 home->max_outstanding = 65535*16;
1070                 home->zombie_period = rc->retry_delay * rc->retry_count;
1071                 if (home->zombie_period == 0) home->zombie_period =30;
1072                 home->response_window = home->zombie_period - 1;
1073
1074                 home->ping_check = HOME_PING_CHECK_NONE;
1075
1076                 home->revive_interval = rc->dead_time;
1077
1078                 if (rbtree_finddata(home_servers_byaddr, home)) {
1079                         cf_log_err(cf_sectiontoitem(cs), "Home server %s has the same IP address and/or port as another home server.", name);
1080                         free(home);
1081                         return 0;
1082                 }
1083
1084                 if (!rbtree_insert(home_servers_byname, home)) {
1085                         cf_log_err(cf_sectiontoitem(cs), "Internal error %d adding home server %s.", __LINE__, name);
1086                         free(home);
1087                         return 0;
1088                 }
1089
1090                 if (!rbtree_insert(home_servers_byaddr, home)) {
1091                         rbtree_deletebydata(home_servers_byname, home);
1092                         cf_log_err(cf_sectiontoitem(cs), "Internal error %d adding home server %s.", __LINE__, name);
1093                         free(home);
1094                         return 0;
1095                 }
1096
1097 #ifdef WITH_STATS
1098                 home->number = home_server_max_number++;
1099                 if (!rbtree_insert(home_servers_bynumber, home)) {
1100                         rbtree_deletebydata(home_servers_byname, home);
1101                         if (home->ipaddr.af != AF_UNSPEC) {
1102                                 rbtree_deletebydata(home_servers_byname, home);
1103                         }
1104                         cf_log_err(cf_sectiontoitem(cs),
1105                                    "Internal error %d adding home server %s.",
1106                                    __LINE__, name);
1107                         free(home);
1108                         return 0;
1109                 }
1110 #endif
1111         }
1112
1113         /*
1114          *      We now have a home server, see if we can insert it
1115          *      into pre-existing pool.
1116          */
1117         if (insert_point >= 0) {
1118                 rad_assert(pool != NULL);
1119                 pool->servers[insert_point] = home;
1120                 return 1;
1121         }
1122
1123         rad_assert(pool == NULL);
1124         rad_assert(home != NULL);
1125
1126         /*
1127          *      Count the old-style realms of this name.
1128          */
1129         num_home_servers = 0;
1130         for (subcs = cf_section_find_next(cs, NULL, "realm");
1131              subcs != NULL;
1132              subcs = cf_section_find_next(cs, subcs, "realm")) {
1133                 const char *this = cf_section_name2(subcs);
1134
1135                 if (!this || (strcmp(this, realm) != 0)) continue;
1136                 num_home_servers++;
1137         }
1138
1139         if (num_home_servers == 0) {
1140                 cf_log_err(cf_sectiontoitem(cs), "Internal error counting pools for home server %s.", name);
1141                 free(home);
1142                 return 0;
1143         }
1144
1145         pool = server_pool_alloc(realm, ldflag, type, num_home_servers);
1146         pool->cs = cs;
1147
1148         pool->servers[0] = home;
1149
1150         if (!rbtree_insert(home_pools_byname, pool)) {
1151                 rad_assert("Internal sanity check failed");
1152                 return 0;
1153         }
1154
1155         *pool_p = pool;
1156
1157         return 1;
1158 #endif
1159 }
1160
1161 static int old_realm_config(realm_config_t *rc, CONF_SECTION *cs, REALM *r)
1162 {
1163         const char *host;
1164         const char *secret = NULL;
1165         home_pool_type_t ldflag;
1166         CONF_PAIR *cp;
1167
1168         cp = cf_pair_find(cs, "ldflag");
1169         ldflag = HOME_POOL_FAIL_OVER;
1170         if (cp) {
1171                 host = cf_pair_value(cp);
1172                 if (!host) {
1173                         cf_log_err(cf_pairtoitem(cp), "No value specified for ldflag");
1174                         return 0;
1175                 }
1176
1177                 if (strcasecmp(host, "fail_over") == 0) {
1178                         cf_log_info(cs, "\tldflag = fail_over");
1179                         
1180                 } else if (strcasecmp(host, "round_robin") == 0) {
1181                         ldflag = HOME_POOL_LOAD_BALANCE;
1182                         cf_log_info(cs, "\tldflag = round_robin");
1183                         
1184                 } else {
1185                         cf_log_err(cf_sectiontoitem(cs), "Unknown value \"%s\" for ldflag", host);
1186                         return 0;
1187                 }
1188         } /* else don't print it. */
1189
1190         /*
1191          *      Allow old-style if it doesn't exist, or if it exists and
1192          *      it's LOCAL.
1193          */
1194         cp = cf_pair_find(cs, "authhost");
1195         if (cp) {
1196                 host = cf_pair_value(cp);
1197                 if (!host) {
1198                         cf_log_err(cf_pairtoitem(cp), "No value specified for authhost");
1199                         return 0;
1200                 }
1201
1202                 if (strcmp(host, "LOCAL") != 0) {
1203                         cp = cf_pair_find(cs, "secret");
1204                         if (!cp) {
1205                                 cf_log_err(cf_sectiontoitem(cs), "No shared secret supplied for realm: %s", r->name);
1206                                 return 0;
1207                         }
1208
1209                         secret = cf_pair_value(cp);
1210                         if (!secret) {
1211                                 cf_log_err(cf_pairtoitem(cp), "No value specified for secret");
1212                                 return 0;
1213                         }
1214                 }
1215                         
1216                 cf_log_info(cs, "\tauthhost = %s",  host);
1217
1218                 if (!old_server_add(rc, cs, r->name, host, secret, ldflag,
1219                                     &r->auth_pool, HOME_TYPE_AUTH, NULL)) {
1220                         return 0;
1221                 }
1222         }
1223
1224         cp = cf_pair_find(cs, "accthost");
1225         if (cp) {
1226                 host = cf_pair_value(cp);
1227                 if (!host) {
1228                         cf_log_err(cf_pairtoitem(cp), "No value specified for accthost");
1229                         return 0;
1230                 }
1231
1232                 /*
1233                  *      Don't look for a secret again if it was found
1234                  *      above.
1235                  */
1236                 if ((strcmp(host, "LOCAL") != 0) && !secret) {
1237                         cp = cf_pair_find(cs, "secret");
1238                         if (!cp) {
1239                                 cf_log_err(cf_sectiontoitem(cs), "No shared secret supplied for realm: %s", r->name);
1240                                 return 0;
1241                         }
1242                         
1243                         secret = cf_pair_value(cp);
1244                         if (!secret) {
1245                                 cf_log_err(cf_pairtoitem(cp), "No value specified for secret");
1246                                 return 0;
1247                         }
1248                 }
1249                 
1250                 cf_log_info(cs, "\taccthost = %s", host);
1251
1252                 if (!old_server_add(rc, cs, r->name, host, secret, ldflag,
1253                                     &r->acct_pool, HOME_TYPE_ACCT, NULL)) {
1254                         return 0;
1255                 }
1256         }
1257
1258         cp = cf_pair_find(cs, "virtual_server");
1259         if (cp) {
1260                 host = cf_pair_value(cp);
1261                 if (!host) {
1262                         cf_log_err(cf_pairtoitem(cp), "No value specified for virtual_server");
1263                         return 0;
1264                 }
1265
1266                 cf_log_info(cs, "\tvirtual_server = %s", host);
1267
1268                 if (!old_server_add(rc, cs, r->name, host, "", ldflag,
1269                                     &r->auth_pool, HOME_TYPE_AUTH, host)) {
1270                         return 0;
1271                 }
1272                 if (!old_server_add(rc, cs, r->name, host, "", ldflag,
1273                                     &r->acct_pool, HOME_TYPE_ACCT, host)) {
1274                         return 0;
1275                 }
1276         }
1277
1278         if (secret) cf_log_info(cs, "\tsecret = %s", secret);
1279
1280         return 1;
1281
1282 }
1283
1284
1285 #ifdef WITH_PROXY
1286 static int add_pool_to_realm(realm_config_t *rc, CONF_SECTION *cs,
1287                              const char *name, home_pool_t **dest,
1288                              int server_type, int do_print)
1289 {
1290         home_pool_t mypool, *pool;
1291
1292         mypool.name = name;
1293         mypool.server_type = server_type;
1294
1295         pool = rbtree_finddata(home_pools_byname, &mypool);
1296         if (!pool) {
1297                 CONF_SECTION *pool_cs;
1298
1299                 pool_cs = cf_section_sub_find_name2(rc->cs,
1300                                                     "home_server_pool",
1301                                                     name);
1302                 if (!pool_cs) {
1303                         pool_cs = cf_section_sub_find_name2(rc->cs,
1304                                                             "server_pool",
1305                                                             name);
1306                 }
1307                 if (!pool_cs) {
1308                         cf_log_err(cf_sectiontoitem(cs), "Failed to find home_server_pool \"%s\"", name);
1309                         return 0;
1310                 }
1311
1312                 if (!server_pool_add(rc, pool_cs, server_type, do_print)) {
1313                         return 0;
1314                 }
1315
1316                 pool = rbtree_finddata(home_pools_byname, &mypool);
1317                 if (!pool) {
1318                         radlog(L_ERR, "Internal sanity check failed in add_pool_to_realm");
1319                         return 0;
1320                 }
1321         }
1322
1323         if (pool->server_type != server_type) {
1324                 cf_log_err(cf_sectiontoitem(cs), "Incompatible home_server_pool \"%s\" (mixed auth_pool / acct_pool)", name);
1325                 return 0;
1326         }
1327
1328         *dest = pool;
1329
1330         return 1;
1331 }
1332 #endif
1333
1334
1335 static int realm_add(realm_config_t *rc, CONF_SECTION *cs)
1336 {
1337         const char *name2;
1338         REALM *r = NULL;
1339         CONF_PAIR *cp;
1340 #ifdef WITH_PROXY
1341         home_pool_t *auth_pool, *acct_pool;
1342         const char *auth_pool_name, *acct_pool_name;
1343 #endif
1344
1345         name2 = cf_section_name1(cs);
1346         if (!name2 || (strcasecmp(name2, "realm") != 0)) {
1347                 cf_log_err(cf_sectiontoitem(cs), "Section is not a realm.");
1348                 return 0;
1349         }
1350
1351         name2 = cf_section_name2(cs);
1352         if (!name2) {
1353                 cf_log_err(cf_sectiontoitem(cs), "Realm section is missing the realm name.");
1354                 return 0;
1355         }
1356
1357 #ifdef WITH_PROXY
1358         auth_pool = acct_pool = NULL;
1359         auth_pool_name = acct_pool_name = NULL;
1360
1361         /*
1362          *      Prefer new configuration to old one.
1363          */
1364         cp = cf_pair_find(cs, "pool");
1365         if (!cp) cp = cf_pair_find(cs, "home_server_pool");
1366         if (cp) auth_pool_name = cf_pair_value(cp);
1367         if (cp && auth_pool_name) {
1368                 acct_pool_name = auth_pool_name;
1369                 if (!add_pool_to_realm(rc, cs,
1370                                        auth_pool_name, &auth_pool,
1371                                        HOME_TYPE_AUTH, 1)) {
1372                         return 0;
1373                 }
1374                 if (!add_pool_to_realm(rc, cs,
1375                                        auth_pool_name, &acct_pool,
1376                                        HOME_TYPE_ACCT, 0)) {
1377                         return 0;
1378                 }
1379         }
1380
1381         cp = cf_pair_find(cs, "auth_pool");
1382         if (cp) auth_pool_name = cf_pair_value(cp);
1383         if (cp && auth_pool_name) {
1384                 if (auth_pool) {
1385                         cf_log_err(cf_sectiontoitem(cs), "Cannot use \"pool\" and \"auth_pool\" at the same time.");
1386                         return 0;
1387                 }
1388                 if (!add_pool_to_realm(rc, cs,
1389                                        auth_pool_name, &auth_pool,
1390                                        HOME_TYPE_AUTH, 1)) {
1391                         return 0;
1392                 }
1393         }
1394
1395         cp = cf_pair_find(cs, "acct_pool");
1396         if (cp) acct_pool_name = cf_pair_value(cp);
1397         if (cp && acct_pool_name) {
1398                 int do_print = TRUE;
1399
1400                 if (acct_pool) {
1401                         cf_log_err(cf_sectiontoitem(cs), "Cannot use \"pool\" and \"acct_pool\" at the same time.");
1402                         return 0;
1403                 }
1404
1405                 if (!auth_pool ||
1406                     (strcmp(auth_pool_name, acct_pool_name) != 0)) {
1407                         do_print = TRUE;
1408                 }
1409
1410                 if (!add_pool_to_realm(rc, cs,
1411                                        acct_pool_name, &acct_pool,
1412                                        HOME_TYPE_ACCT, do_print)) {
1413                         return 0;
1414                 }
1415         }
1416 #endif
1417
1418         cf_log_info(cs, " realm %s {", name2);
1419
1420 #ifdef WITH_PROXY
1421         /*
1422          *      The realm MAY already exist if it's an old-style realm.
1423          *      In that case, merge the old-style realm with this one.
1424          */
1425         r = realm_find2(name2);
1426         if (r && (strcmp(r->name, name2) == 0)) {
1427                 if (cf_pair_find(cs, "auth_pool") ||
1428                     cf_pair_find(cs, "acct_pool")) {
1429                         cf_log_err(cf_sectiontoitem(cs), "Duplicate realm \"%s\"", name2);
1430                         goto error;
1431                 }
1432
1433                 if (!old_realm_config(rc, cs, r)) {
1434                         goto error;
1435                 }
1436
1437                 cf_log_info(cs, " } # realm %s", name2);
1438                 return 1;
1439         }
1440 #endif
1441
1442 #ifdef HAVE_REGEX_H
1443         if (name2[0] == '~') {
1444                 regex_t reg;
1445                 
1446                 /*
1447                  *      Include substring matches.
1448                  */
1449                 if (regcomp(&reg, name2 + 1,
1450                             REG_EXTENDED | REG_NOSUB | REG_ICASE) != 0) {
1451                         cf_log_err(cf_sectiontoitem(cs),
1452                                    "Invalid regex in realm \"%s\"", name2);
1453                         goto error;
1454                 }
1455                 regfree(&reg);
1456         }
1457 #endif
1458
1459         r = rad_malloc(sizeof(*r));
1460         memset(r, 0, sizeof(*r));
1461
1462         r->name = name2;
1463         r->striprealm = 1;
1464 #ifdef WITH_PROXY
1465         r->auth_pool = auth_pool;
1466         r->acct_pool = acct_pool;
1467         
1468         if (auth_pool_name &&
1469             (auth_pool_name == acct_pool_name)) { /* yes, ptr comparison */
1470                 cf_log_info(cs, "\tpool = %s", auth_pool_name);
1471         } else {
1472                 if (auth_pool_name) cf_log_info(cs, "\tauth_pool = %s", auth_pool_name);
1473                 if (acct_pool_name) cf_log_info(cs, "\tacct_pool = %s", acct_pool_name);
1474         }
1475 #endif
1476
1477         cp = cf_pair_find(cs, "nostrip");
1478         if (cp && (cf_pair_value(cp) == NULL)) {
1479                 r->striprealm = 0;
1480                 cf_log_info(cs, "\tnostrip");
1481         }
1482
1483         /*
1484          *      We're a new-style realm.  Complain if we see the old
1485          *      directives.
1486          */
1487         if (r->auth_pool || r->acct_pool) {
1488                 if (((cp = cf_pair_find(cs, "authhost")) != NULL) ||
1489                     ((cp = cf_pair_find(cs, "accthost")) != NULL) ||
1490                     ((cp = cf_pair_find(cs, "secret")) != NULL) ||
1491                     ((cp = cf_pair_find(cs, "ldflag")) != NULL)) {
1492                         DEBUG2("WARNING: Ignoring old-style configuration entry \"%s\" in realm \"%s\"", cf_pair_attr(cp), r->name);
1493                 }
1494
1495
1496                 /*
1497                  *      The realm MAY be an old-style realm, as there
1498                  *      was no auth_pool or acct_pool.  Double-check
1499                  *      it, just to be safe.
1500                  */
1501         } else if (!old_realm_config(rc, cs, r)) {
1502                 goto error;
1503         }
1504
1505 #ifdef HAVE_REGEX_H
1506         /*
1507          *      It's a regex.  Add it to a separate list.
1508          */
1509         if (name2[0] == '~') {
1510                 realm_regex_t *rr, **last;
1511
1512                 rr = rad_malloc(sizeof(*rr));
1513                 
1514                 last = &realms_regex;
1515                 while (*last) last = &((*last)->next);  /* O(N^2)... sue me. */
1516
1517                 r->name = name2;
1518                 rr->realm = r;
1519                 rr->next = NULL;
1520
1521                 *last = rr;
1522
1523                 cf_log_info(cs, " }");
1524                 return 1;
1525         }
1526 #endif
1527
1528         if (!rbtree_insert(realms_byname, r)) {
1529                 rad_assert("Internal sanity check failed");
1530                 goto error;
1531         }
1532
1533         cf_log_info(cs, " }");
1534
1535         return 1;
1536
1537  error:
1538         cf_log_info(cs, " } # realm %s", name2);
1539         free(r);
1540         return 0;
1541 }
1542
1543 #ifdef WITH_COA
1544 static int pool_peek_type(CONF_SECTION *cs)
1545 {
1546         const char *name;
1547         CONF_PAIR *cp;
1548         home_server *home;
1549
1550         cp = cf_pair_find(cs, "home_server");
1551         if (!cp) {
1552                 cf_log_err(cf_sectiontoitem(cs), "Pool does not contain a \"home_server\" entry");
1553                 return HOME_TYPE_INVALID;
1554         }
1555
1556         name = cf_pair_value(cp);
1557         if (!name) {
1558                 cf_log_err(cf_pairtoitem(cp), "home_server entry does not reference a home server");
1559                 return HOME_TYPE_INVALID;
1560         }
1561
1562         home = home_server_byname(name);
1563         if (!home) {
1564                 cf_log_err(cf_pairtoitem(cp), "home_server \"%s\" does not exist", name);
1565                 return HOME_TYPE_INVALID;
1566         }
1567
1568         return home->type;
1569 }
1570 #endif
1571
1572 int realms_init(CONF_SECTION *config)
1573 {
1574         CONF_SECTION *cs;
1575         realm_config_t *rc, *old_rc;
1576
1577         if (realms_byname) return 1;
1578
1579         realms_byname = rbtree_create(realm_name_cmp, free, 0);
1580         if (!realms_byname) {
1581                 realms_free();
1582                 return 0;
1583         }
1584
1585 #ifdef WITH_PROXY
1586         home_servers_byaddr = rbtree_create(home_server_addr_cmp, free, 0);
1587         if (!home_servers_byaddr) {
1588                 realms_free();
1589                 return 0;
1590         }
1591
1592         home_servers_byname = rbtree_create(home_server_name_cmp, NULL, 0);
1593         if (!home_servers_byname) {
1594                 realms_free();
1595                 return 0;
1596         }
1597
1598 #ifdef WITH_STATS
1599         home_servers_bynumber = rbtree_create(home_server_number_cmp, NULL, 0);
1600         if (!home_servers_bynumber) {
1601                 realms_free();
1602                 return 0;
1603         }
1604 #endif
1605
1606         home_pools_byname = rbtree_create(home_pool_name_cmp, free, 0);
1607         if (!home_pools_byname) {
1608                 realms_free();
1609                 return 0;
1610         }
1611 #endif
1612
1613         rc = rad_malloc(sizeof(*rc));
1614         memset(rc, 0, sizeof(*rc));
1615         rc->cs = config;
1616
1617 #ifdef WITH_PROXY
1618         cs = cf_subsection_find_next(config, NULL, "proxy");
1619         if (cs) {
1620                 cf_section_parse(cs, rc, proxy_config);
1621         } else {
1622                 rc->dead_time = DEAD_TIME;
1623                 rc->retry_count = RETRY_COUNT;
1624                 rc->retry_delay = RETRY_DELAY;
1625                 rc->fallback = 0;
1626                 rc->wake_all_if_all_dead= 0;
1627         }
1628 #endif
1629
1630         for (cs = cf_subsection_find_next(config, NULL, "realm");
1631              cs != NULL;
1632              cs = cf_subsection_find_next(config, cs, "realm")) {
1633                 if (!realm_add(rc, cs)) {
1634                         free(rc);
1635                         realms_free();
1636                         return 0;
1637                 }
1638         }
1639
1640 #ifdef WITH_COA
1641         /*
1642          *      CoA pools aren't tied to realms.
1643          */
1644         for (cs = cf_subsection_find_next(config, NULL, "home_server_pool");
1645              cs != NULL;
1646              cs = cf_subsection_find_next(config, cs, "home_server_pool")) {
1647                 int type;
1648
1649                 if (cf_data_find(cs, "home_server_pool")) continue;
1650
1651                 type = pool_peek_type(cs);
1652                 if (type == HOME_TYPE_INVALID) return 0;
1653
1654                 if (!server_pool_add(rc, cs, type, TRUE)) {
1655                         return 0;
1656                 }
1657         }
1658 #endif
1659
1660
1661 #ifdef WITH_PROXY
1662         xlat_register("home_server", xlat_home_server, NULL);
1663         xlat_register("home_server_pool", xlat_server_pool, NULL);
1664 #endif
1665
1666         /*
1667          *      Swap pointers atomically.
1668          */
1669         old_rc = realm_config;
1670         realm_config = rc;
1671         free(old_rc);
1672
1673         return 1;
1674 }
1675
1676 /*
1677  *      Find a realm where "name" might be the regex.
1678  */
1679 REALM *realm_find2(const char *name)
1680 {
1681         REALM myrealm;
1682         REALM *realm;
1683         
1684         if (!name) name = "NULL";
1685
1686         myrealm.name = name;
1687         realm = rbtree_finddata(realms_byname, &myrealm);
1688         if (realm) return realm;
1689
1690 #ifdef HAVE_REGEX_H
1691         if (realms_regex) {
1692                 realm_regex_t *this;
1693
1694                 for (this = realms_regex; this != NULL; this = this->next) {
1695                         if (strcmp(this->realm->name, name) == 0) {
1696                                 return this->realm;
1697                         }
1698                 }
1699         }
1700 #endif
1701
1702         /*
1703          *      Couldn't find a realm.  Look for DEFAULT.
1704          */
1705         myrealm.name = "DEFAULT";
1706         return rbtree_finddata(realms_byname, &myrealm);
1707 }
1708
1709
1710 /*
1711  *      Find a realm in the REALM list.
1712  */
1713 REALM *realm_find(const char *name)
1714 {
1715         REALM myrealm;
1716         REALM *realm;
1717         
1718         if (!name) name = "NULL";
1719
1720         myrealm.name = name;
1721         realm = rbtree_finddata(realms_byname, &myrealm);
1722         if (realm) return realm;
1723
1724 #ifdef HAVE_REGEX_H
1725         if (realms_regex) {
1726                 realm_regex_t *this;
1727
1728                 for (this = realms_regex; this != NULL; this = this->next) {
1729                         int compare;
1730                         regex_t reg;
1731
1732                         /*
1733                          *      Include substring matches.
1734                          */
1735                         if (regcomp(&reg, this->realm->name + 1,
1736                                     REG_EXTENDED | REG_NOSUB | REG_ICASE) != 0) {
1737                                 continue;
1738                         }
1739
1740                         compare = regexec(&reg, name, 0, NULL, 0);
1741                         regfree(&reg);
1742
1743                         if (compare == 0) return this->realm;
1744                 }
1745         }
1746 #endif
1747
1748         /*
1749          *      Couldn't find a realm.  Look for DEFAULT.
1750          */
1751         myrealm.name = "DEFAULT";
1752         return rbtree_finddata(realms_byname, &myrealm);
1753 }
1754
1755
1756 #ifdef WITH_PROXY
1757 home_server *home_server_ldb(const char *realmname,
1758                              home_pool_t *pool, REQUEST *request)
1759 {
1760         int             start;
1761         int             count;
1762         home_server     *found = NULL;
1763         VALUE_PAIR      *vp;
1764
1765         start = 0;
1766
1767         /*
1768          *      Determine how to pick choose the home server.
1769          */
1770         switch (pool->type) {
1771                 uint32_t hash;
1772
1773                 /*
1774                  *      For load-balancing by client IP address, we
1775                  *      pick a home server by hashing the client IP.
1776                  *
1777                  *      This isn't as even a load distribution as
1778                  *      tracking the State attribute, but it's better
1779                  *      than nothing.
1780                  */
1781         case HOME_POOL_CLIENT_BALANCE:
1782                 switch (request->packet->src_ipaddr.af) {
1783                 case AF_INET:
1784                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
1785                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
1786                         break;
1787                 case AF_INET6:
1788                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
1789                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
1790                         break;
1791                 default:
1792                         hash = 0;
1793                         break;
1794                 }
1795                 start = hash % pool->num_home_servers;
1796                 break;
1797
1798         case HOME_POOL_CLIENT_PORT_BALANCE:
1799                 switch (request->packet->src_ipaddr.af) {
1800                 case AF_INET:
1801                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
1802                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
1803                         break;
1804                 case AF_INET6:
1805                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
1806                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
1807                         break;
1808                 default:
1809                         hash = 0;
1810                         break;
1811                 }
1812                 fr_hash_update(&request->packet->src_port,
1813                                  sizeof(request->packet->src_port), hash);
1814                 start = hash % pool->num_home_servers;
1815                 break;
1816
1817         case HOME_POOL_KEYED_BALANCE:
1818                 if ((vp = pairfind(request->config_items, PW_LOAD_BALANCE_KEY)) != NULL) {
1819                         hash = fr_hash(vp->vp_strvalue, vp->length);
1820                         start = hash % pool->num_home_servers;
1821                         break;
1822                 }
1823                 /* FALL-THROUGH */
1824                                 
1825         case HOME_POOL_LOAD_BALANCE:
1826                 found = pool->servers[0];
1827
1828         default:
1829                 start = 0;
1830                 break;
1831         }
1832
1833         /*
1834          *      Starting with the home server we chose, loop through
1835          *      all home servers.  If the current one is dead, skip
1836          *      it.  If it is too busy, skip it.
1837          *
1838          *      Otherwise, use it.
1839          */
1840         for (count = 0; count < pool->num_home_servers; count++) {
1841                 home_server *home = pool->servers[(start + count) % pool->num_home_servers];
1842
1843                 if (home->state == HOME_STATE_IS_DEAD) {
1844                         continue;
1845                 }
1846
1847                 /*
1848                  *      This home server is too busy.  Choose another one.
1849                  */
1850                 if (home->currently_outstanding >= home->max_outstanding) {
1851                         continue;
1852                 }
1853
1854 #ifdef WITH_DETAIL
1855                 /*
1856                  *      We read the packet from a detail file, AND it
1857                  *      came from this server.  Don't re-proxy it
1858                  *      there.
1859                  */
1860                 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
1861                     (request->packet->code == PW_ACCOUNTING_REQUEST) &&
1862                     (fr_ipaddr_cmp(&home->ipaddr, &request->packet->src_ipaddr) == 0)) {
1863                         continue;
1864                 }
1865 #endif
1866
1867                 if (pool->type != HOME_POOL_LOAD_BALANCE) {
1868                         return home;
1869                 }
1870
1871                 if (!found) {
1872                         found = home;
1873                         continue;
1874                 }
1875
1876                 RDEBUG3("PROXY %s %d\t%s %d",
1877                        found->name, found->currently_outstanding,
1878                        home->name, home->currently_outstanding);
1879
1880                 /*
1881                  *      Prefer this server if it's less busy than the
1882                  *      one we previously found.
1883                  */
1884                 if (home->currently_outstanding < found->currently_outstanding) {
1885                         RDEBUG3("PROXY Choosing %s: It's less busy than %s",
1886                                home->name, found->name);
1887                         found = home;
1888                         continue;
1889                 }
1890
1891                 /*
1892                  *      Ignore servers which are busier than the one
1893                  *      we found.
1894                  */
1895                 if (home->currently_outstanding > found->currently_outstanding) {
1896                         RDEBUG3("PROXY Skipping %s: It's busier than %s",
1897                                home->name, found->name);
1898                         continue;
1899                 }
1900
1901                 /*
1902                  *      From the list of servers which have the same
1903                  *      load, choose one at random.
1904                  */
1905                 if (((count + 1) * (fr_rand() & 0xffff)) < (uint32_t) 0x10000) {
1906                         found = home;
1907                 }
1908
1909         } /* loop over the home servers */
1910
1911         if (found) return found;
1912
1913         /*
1914          *      There's a fallback if they're all dead.
1915          */
1916         if (pool->fallback) {
1917                 return pool->fallback;
1918         }
1919
1920         /*
1921          *      No live match found, and no fallback to the "DEFAULT"
1922          *      realm.  We fix this by blindly marking all servers as
1923          *      "live".  But only do it for ones that don't support
1924          *      "pings", as they will be marked live when they
1925          *      actually are live.
1926          */
1927         if (!realm_config->fallback &&
1928             realm_config->wake_all_if_all_dead) {
1929                 home_server *lb = NULL;
1930
1931                 for (count = 0; count < pool->num_home_servers; count++) {
1932                         home_server *home = pool->servers[count];
1933
1934                         if ((home->state == HOME_STATE_IS_DEAD) &&
1935                             (home->ping_check == HOME_PING_CHECK_NONE)) {
1936                                 home->state = HOME_STATE_ALIVE;
1937                                 if (!lb) lb = home;
1938                         }
1939                 }
1940
1941                 if (lb) return lb;
1942         }
1943
1944         /*
1945          *      Still nothing.  Look up the DEFAULT realm, but only
1946          *      if we weren't looking up the NULL or DEFAULT realms.
1947          */
1948         if (realm_config->fallback &&
1949             realmname &&
1950             (strcmp(realmname, "NULL") != 0) &&
1951             (strcmp(realmname, "DEFAULT") != 0)) {
1952                 REALM *rd = realm_find("DEFAULT");
1953
1954                 if (!rd) return NULL;
1955
1956                 pool = NULL;
1957                 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1958                         pool = rd->auth_pool;
1959
1960                 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1961                         pool = rd->acct_pool;
1962                 }
1963                 if (!pool) return NULL;
1964
1965                 RDEBUG2("PROXY - realm %s has no live home servers.  Falling back to the DEFAULT realm.", realmname);
1966                 return home_server_ldb(rd->name, pool, request);
1967         }
1968
1969         /*
1970          *      Still haven't found anything.  Oh well.
1971          */
1972         return NULL;
1973 }
1974
1975
1976 home_server *home_server_find(fr_ipaddr_t *ipaddr, int port)
1977 {
1978         home_server myhome;
1979
1980         memset(&myhome, 0, sizeof(myhome));
1981         myhome.ipaddr = *ipaddr;
1982         myhome.port = port;
1983         myhome.server = NULL;   /* we're not called for internal proxying */
1984
1985         return rbtree_finddata(home_servers_byaddr, &myhome);
1986 }
1987
1988 #ifdef WITH_COA
1989 home_server *home_server_byname(const char *name)
1990 {
1991         home_server myhome;
1992
1993         memset(&myhome, 0, sizeof(myhome));
1994         myhome.name = name;
1995
1996         return rbtree_finddata(home_servers_byname, &myhome);
1997 }
1998 #endif
1999
2000 #ifdef WITH_STATS
2001 home_server *home_server_bynumber(int number)
2002 {
2003         home_server myhome;
2004
2005         memset(&myhome, 0, sizeof(myhome));
2006         myhome.number = number;
2007         myhome.server = NULL;   /* we're not called for internal proxying */
2008
2009         return rbtree_finddata(home_servers_bynumber, &myhome);
2010 }
2011 #endif
2012
2013 home_pool_t *home_pool_byname(const char *name, int type)
2014 {
2015         home_pool_t mypool;
2016         
2017         memset(&mypool, 0, sizeof(mypool));
2018         mypool.name = name;
2019         mypool.server_type = type;
2020         return rbtree_finddata(home_pools_byname, &mypool);
2021 }
2022
2023 #endif