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