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