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