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