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