Convert rad_alloc and rad_free to use talloc
[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_PCREPOSIX_H
36 #include <pcreposix.h>
37 #else
38 #ifdef HAVE_REGEX_H
39 #include <regex.h>
40
41 /*
42  *  For POSIX Regular expressions.
43  *  (0) Means no extended regular expressions.
44  *  REG_EXTENDED means use extended regular expressions.
45  */
46 #ifndef REG_EXTENDED
47 #define REG_EXTENDED (0)
48 #endif
49
50 #ifndef REG_NOSUB
51 #define REG_NOSUB (0)
52 #endif
53
54 #ifndef REG_ICASE
55 #define REG_ICASE (0)
56 #endif
57 #endif
58 #endif
59
60 static rbtree_t *realms_byname = NULL;
61
62 #ifdef HAVE_REGEX_H
63 typedef struct realm_regex_t {
64         REALM   *realm;
65         struct realm_regex_t *next;
66 } realm_regex_t;
67
68 static realm_regex_t *realms_regex = NULL;
69
70 #endif /* HAVE_REGEX_H */
71
72 typedef struct realm_config_t {
73         CONF_SECTION    *cs;
74         int             dead_time;
75         int             retry_count;
76         int             retry_delay;
77         int             fallback;
78         int             wake_all_if_all_dead;
79 } realm_config_t;
80
81 static realm_config_t *realm_config = NULL;
82
83 #ifdef WITH_PROXY
84 static rbtree_t *home_servers_byaddr = NULL;
85 static rbtree_t *home_servers_byname = NULL;
86 #ifdef WITH_STATS
87 static int home_server_max_number = 0;
88 static rbtree_t *home_servers_bynumber = NULL;
89 #endif
90
91 static rbtree_t *home_pools_byname = NULL;
92
93 /*
94  *  Map the proxy server configuration parameters to variables.
95  */
96 static const CONF_PARSER proxy_config[] = {
97         { "retry_delay",  PW_TYPE_INTEGER,
98           offsetof(realm_config_t, retry_delay),
99           NULL, Stringify(RETRY_DELAY) },
100
101         { "retry_count",  PW_TYPE_INTEGER,
102           offsetof(realm_config_t, retry_count),
103           NULL, Stringify(RETRY_COUNT) },
104
105         { "default_fallback", PW_TYPE_BOOLEAN,
106           offsetof(realm_config_t, fallback),
107           NULL, "no" },
108
109         { "dead_time",    PW_TYPE_INTEGER, 
110           offsetof(realm_config_t, dead_time),
111           NULL, Stringify(DEAD_TIME) },
112
113         { "wake_all_if_all_dead", PW_TYPE_BOOLEAN,
114           offsetof(realm_config_t, wake_all_if_all_dead),
115           NULL, "no" },
116
117         { NULL, -1, 0, NULL, NULL }
118 };
119 #endif
120
121 static int realm_name_cmp(const void *one, const void *two)
122 {
123         const REALM *a = one;
124         const REALM *b = two;
125
126         return strcasecmp(a->name, b->name);
127 }
128
129
130 #ifdef WITH_PROXY
131 static void home_server_free(void *data)
132 {
133         home_server *home = data;
134
135         free(home);
136 }
137
138 static int home_server_name_cmp(const void *one, const void *two)
139 {
140         const home_server *a = one;
141         const home_server *b = two;
142
143         if (a->type < b->type) return -1;
144         if (a->type > b->type) return +1;
145
146         return strcasecmp(a->name, b->name);
147 }
148
149 static int home_server_addr_cmp(const void *one, const void *two)
150 {
151         int rcode;
152         const home_server *a = one;
153         const home_server *b = two;
154
155         if (a->server && !b->server) return -1;
156         if (!a->server && b->server) return +1;
157         if (a->server && b->server) {
158                 rcode = a->type - b->type;
159                 if (rcode != 0) return rcode;
160                 return strcmp(a->server, b->server);
161         }
162
163         if (a->port < b->port) return -1;
164         if (a->port > b->port) return +1;
165
166 #ifdef WITH_TCP
167         if (a->proto < b->proto) return -1;
168         if (a->proto > b->proto) return +1;
169 #endif
170
171         rcode = fr_ipaddr_cmp(&a->src_ipaddr, &b->src_ipaddr);
172         if (rcode != 0) return rcode;
173
174         return fr_ipaddr_cmp(&a->ipaddr, &b->ipaddr);
175 }
176
177 #ifdef WITH_STATS
178 static int home_server_number_cmp(const void *one, const void *two)
179 {
180         const home_server *a = one;
181         const home_server *b = two;
182
183         return (a->number - b->number);
184 }
185 #endif
186
187 static int home_pool_name_cmp(const void *one, const void *two)
188 {
189         const home_pool_t *a = one;
190         const home_pool_t *b = two;
191
192         if (a->server_type < b->server_type) return -1;
193         if (a->server_type > b->server_type) return +1;
194
195         return strcasecmp(a->name, b->name);
196 }
197
198
199 static size_t xlat_cs(CONF_SECTION *cs, const char *fmt, char *out, size_t outlen)
200
201 {
202         const char *value = NULL;
203
204         /*
205          *      Instance name
206          */
207         if (strcmp(fmt, "instance") == 0) {
208                 value = cf_section_name2(cs);
209                 if (!value) {
210                         *out = '\0';
211                         return 0;
212                 }
213         } else {
214                 CONF_PAIR *cp;
215
216                 cp = cf_pair_find(cs, fmt);
217                 if (!cp || !(value = cf_pair_value(cp))) {
218                         *out = '\0';
219                         return 0;
220                 }
221         }
222
223         strlcpy(out, value, outlen);
224
225         return strlen(out);
226 }
227
228
229 /*
230  *      Xlat for %{home_server:foo}
231  */
232 static size_t xlat_home_server(UNUSED void *instance, REQUEST *request,
233                                const char *fmt, char *out, size_t outlen)
234 {
235         if (!fmt || !out || (outlen < 1)) return 0;
236
237         if (!request || !request->home_server) {
238                 *out = '\0';
239                 return 0;
240         }
241
242         return xlat_cs(request->home_server->cs, fmt, out, outlen);
243 }
244
245
246 /*
247  *      Xlat for %{home_server_pool:foo}
248  */
249 static size_t xlat_server_pool(UNUSED void *instance, REQUEST *request,
250                                const char *fmt, char *out, size_t outlen)
251 {
252         if (!fmt || !out || (outlen < 1)) return 0;
253
254         if (!request || !request->home_pool) {
255                 *out = '\0';
256                 return 0;
257         }
258
259         return xlat_cs(request->home_pool->cs, fmt, out, outlen);
260 }
261 #endif
262
263 void realms_free(void)
264 {
265 #ifdef WITH_PROXY
266 #ifdef WITH_STATS
267         rbtree_free(home_servers_bynumber);
268         home_servers_bynumber = NULL;
269 #endif
270
271         rbtree_free(home_servers_byname);
272         home_servers_byname = NULL;
273
274         rbtree_free(home_servers_byaddr);
275         home_servers_byaddr = NULL;
276
277         rbtree_free(home_pools_byname);
278         home_pools_byname = NULL;
279 #endif
280
281         rbtree_free(realms_byname);
282         realms_byname = NULL;
283
284 #ifdef HAVE_REGEX_H
285         if (realms_regex) {
286                 realm_regex_t *this, *next;
287
288                 for (this = realms_regex; this != NULL; this = next) {
289                         next = this->next;
290                         free(this->realm);
291                         free(this);
292                 }
293                 realms_regex = NULL;
294         }
295 #endif
296
297         free(realm_config);
298         realm_config = NULL;
299 }
300
301
302 #ifdef WITH_PROXY
303 static CONF_PARSER limit_config[] = {
304         { "max_connections", PW_TYPE_INTEGER,
305           offsetof(home_server, limit.max_connections), NULL,   "16" },
306
307         { "max_requests", PW_TYPE_INTEGER,
308           offsetof(home_server, limit.max_requests), NULL,   "0" },
309
310         { "lifetime", PW_TYPE_INTEGER,
311           offsetof(home_server, limit.lifetime), NULL,   "0" },
312
313         { "idle_timeout", PW_TYPE_INTEGER,
314           offsetof(home_server, limit.idle_timeout), NULL,   "0" },
315
316         { NULL, -1, 0, NULL, NULL }             /* end the list */
317 };
318
319 static struct in_addr hs_ip4addr;
320 static struct in6_addr hs_ip6addr;
321 static char *hs_srcipaddr = NULL;
322 static char *hs_type = NULL;
323 static char *hs_check = NULL;
324 static char *hs_virtual_server = NULL;
325 #ifdef WITH_TCP
326 static char *hs_proto = NULL;
327 #endif
328
329 #ifdef WITH_COA
330 static CONF_PARSER home_server_coa[] = {
331         { "irt",  PW_TYPE_INTEGER,
332           offsetof(home_server, coa_irt), 0, Stringify(2) },
333         { "mrt",  PW_TYPE_INTEGER,
334           offsetof(home_server, coa_mrt), 0, Stringify(16) },
335         { "mrc",  PW_TYPE_INTEGER,
336           offsetof(home_server, coa_mrc), 0, Stringify(5) },
337         { "mrd",  PW_TYPE_INTEGER,
338           offsetof(home_server, coa_mrd), 0, Stringify(30) },
339
340         { NULL, -1, 0, NULL, NULL }             /* end the list */
341 };
342 #endif
343
344 static CONF_PARSER home_server_config[] = {
345         { "ipaddr",  PW_TYPE_IPADDR,
346           0, &hs_ip4addr,  NULL },
347         { "ipv6addr",  PW_TYPE_IPV6ADDR,
348           0, &hs_ip6addr, NULL },
349         { "virtual_server",  PW_TYPE_STRING_PTR,
350           0, &hs_virtual_server, NULL },
351
352         { "port", PW_TYPE_INTEGER,
353           offsetof(home_server,port), NULL,   "0" },
354
355         { "type",  PW_TYPE_STRING_PTR,
356           0, &hs_type, NULL },
357
358 #ifdef WITH_TCP
359         { "proto",  PW_TYPE_STRING_PTR,
360           0, &hs_proto, NULL },
361 #endif
362
363         { "secret",  PW_TYPE_STRING_PTR,
364           offsetof(home_server,secret), NULL,  NULL},
365
366         { "src_ipaddr",  PW_TYPE_STRING_PTR,
367           0, &hs_srcipaddr,  NULL },
368
369         { "response_window", PW_TYPE_INTEGER,
370           offsetof(home_server,response_window), NULL,   "30" },
371         { "max_outstanding", PW_TYPE_INTEGER,
372           offsetof(home_server,max_outstanding), NULL,   "65536" },
373
374         { "zombie_period", PW_TYPE_INTEGER,
375           offsetof(home_server,zombie_period), NULL,   "40" },
376         { "status_check", PW_TYPE_STRING_PTR,
377           0, &hs_check,   "none" },
378         { "ping_check", PW_TYPE_STRING_PTR,
379           0, &hs_check,   NULL },
380
381         { "ping_interval", PW_TYPE_INTEGER,
382           offsetof(home_server,ping_interval), NULL,   "30" },
383         { "check_interval", PW_TYPE_INTEGER,
384           offsetof(home_server,ping_interval), NULL,   "30" },
385         { "num_answers_to_alive", PW_TYPE_INTEGER,
386           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
387         { "revive_interval", PW_TYPE_INTEGER,
388           offsetof(home_server,revive_interval), NULL,   "300" },
389         { "status_check_timeout", PW_TYPE_INTEGER,
390           offsetof(home_server,ping_timeout), NULL,   "4" },
391
392         { "username",  PW_TYPE_STRING_PTR,
393           offsetof(home_server,ping_user_name), NULL,  NULL},
394         { "password",  PW_TYPE_STRING_PTR,
395           offsetof(home_server,ping_user_password), NULL,  NULL},
396
397 #ifdef WITH_STATS
398         { "historic_average_window", PW_TYPE_INTEGER,
399           offsetof(home_server,ema.window), NULL,  NULL },
400 #endif
401
402 #ifdef WITH_COA
403         {  "coa", PW_TYPE_SUBSECTION, 0, NULL, (const void *) home_server_coa },
404 #endif
405
406         { "limit", PW_TYPE_SUBSECTION, 0, NULL, (const void *) limit_config },
407
408         { NULL, -1, 0, NULL, NULL }             /* end the list */
409 };
410
411
412 static void null_free(UNUSED void *data)
413 {
414 }
415
416 static int home_server_add(realm_config_t *rc, CONF_SECTION *cs)
417 {
418         const char *name2;
419         home_server *home;
420         int dual = FALSE;
421         CONF_PAIR *cp;
422         CONF_SECTION *tls;
423
424         hs_virtual_server = NULL;
425
426         name2 = cf_section_name2(cs);
427         if (!name2) {
428                 cf_log_err(cf_sectiontoitem(cs),
429                            "Home server section is missing a name.");
430                 return 0;
431         }
432
433         home = rad_malloc(sizeof(*home));
434         memset(home, 0, sizeof(*home));
435
436         home->name = name2;
437         home->cs = cs;
438         home->state = HOME_STATE_UNKNOWN;
439
440         /*
441          *      Last packet sent / received are zero.
442          */
443
444         memset(&hs_ip4addr, 0, sizeof(hs_ip4addr));
445         memset(&hs_ip6addr, 0, sizeof(hs_ip6addr));
446         if (cf_section_parse(cs, home, home_server_config) < 0) {
447                 goto error;
448         }
449
450         /*
451          *      Figure out which one to use.
452          */
453         if (cf_pair_find(cs, "ipaddr")) {
454                 home->ipaddr.af = AF_INET;
455                 home->ipaddr.ipaddr.ip4addr = hs_ip4addr;
456
457         } else if (cf_pair_find(cs, "ipv6addr")) {
458                 home->ipaddr.af = AF_INET6;
459                 home->ipaddr.ipaddr.ip6addr = hs_ip6addr;
460
461         } else if ((cp = cf_pair_find(cs, "virtual_server")) != NULL) {
462                 home->ipaddr.af = AF_UNSPEC;
463                 home->server = cf_pair_value(cp);
464                 if (!home->server) {
465                         cf_log_err(cf_sectiontoitem(cs),
466                                    "Invalid value for virtual_server");
467                         goto error;
468                 }
469
470                 if (!cf_section_sub_find_name2(rc->cs, "server", home->server)) {
471                   
472                         cf_log_err(cf_sectiontoitem(cs),
473                                    "No such server %s", home->server);
474                         goto error;
475                 }
476
477                 /*
478                  *      When CoA is used, the user has to specify the type
479                  *      of the home server, even when they point to
480                  *      virtual servers.
481                  */
482                 home->secret = strdup("");
483                 goto skip_port;
484
485         } else {
486                 cf_log_err(cf_sectiontoitem(cs),
487                            "No ipaddr, ipv6addr, or virtual_server defined for home server \"%s\".",
488                            name2);
489         error:
490                 hs_type = NULL;
491                 hs_check = NULL;
492                 hs_srcipaddr = NULL;
493 #ifdef WITH_TCP
494                 hs_proto = NULL;
495 #endif
496                 return 0;
497         }
498
499         if (!home->port || (home->port > 65535)) {
500                 cf_log_err(cf_sectiontoitem(cs),
501                            "No port, or invalid port defined for home server %s.",
502                            name2);
503                 goto error;
504         }
505
506         if (0) {
507                 cf_log_err(cf_sectiontoitem(cs),
508                            "Fatal error!  Home server %s is ourselves!",
509                            name2);
510                 goto error;
511         }
512
513         if (!home->secret) {
514                 cf_log_err(cf_sectiontoitem(cs),
515                            "No shared secret defined for home server %s.",
516                            name2);
517                 goto error;
518         }
519
520         /*
521          *      Use a reasonable default.
522          */
523  skip_port:
524         if (!hs_type) hs_type = strdup("auth+acct");
525
526         if (strcasecmp(hs_type, "auth") == 0) {
527                 home->type = HOME_TYPE_AUTH;
528
529         } else if (strcasecmp(hs_type, "acct") == 0) {
530                 home->type = HOME_TYPE_ACCT;
531
532         } else if (strcasecmp(hs_type, "auth+acct") == 0) {
533                 home->type = HOME_TYPE_AUTH;
534                 dual = TRUE;
535
536 #ifdef WITH_COA
537         } else if (strcasecmp(hs_type, "coa") == 0) {
538                 home->type = HOME_TYPE_COA;
539                 dual = FALSE;
540
541                 if (home->server != NULL) {
542                         cf_log_err(cf_sectiontoitem(cs),
543                                    "Home servers of type \"coa\" cannot point to a virtual server");
544                         goto error;
545                 }
546 #endif
547
548         } else {
549                 cf_log_err(cf_sectiontoitem(cs),
550                            "Invalid type \"%s\" for home server %s.",
551                            hs_type, name2);
552                 goto error;
553         }
554         hs_type = NULL;
555
556         if (!hs_check || (strcasecmp(hs_check, "none") == 0)) {
557                 home->ping_check = HOME_PING_CHECK_NONE;
558
559         } else if (strcasecmp(hs_check, "status-server") == 0) {
560                 home->ping_check = HOME_PING_CHECK_STATUS_SERVER;
561
562         } else if (strcasecmp(hs_check, "request") == 0) {
563                 home->ping_check = HOME_PING_CHECK_REQUEST;
564
565                 if (!home->ping_user_name ||
566                     !*home->ping_user_name) {
567                         cf_log_err(cf_sectiontoitem(cs), "You must supply a 'username' to enable status_check=request");
568                         goto error;
569                 }
570
571                 if ((home->type == HOME_TYPE_AUTH) &&
572                     (!home->ping_user_password ||
573                      !*home->ping_user_password)) {
574                         cf_log_err(cf_sectiontoitem(cs), "You must supply a password to enable status_check=request");
575                         goto error;
576                 }
577
578         } else {
579                 cf_log_err(cf_sectiontoitem(cs),
580                            "Invalid status__check \"%s\" for home server %s.",
581                            hs_check, name2);
582                 goto error;
583         }
584         hs_check = NULL;
585
586         if ((home->ping_check != HOME_PING_CHECK_NONE) &&
587             (home->ping_check != HOME_PING_CHECK_STATUS_SERVER)) {
588                 if (!home->ping_user_name) {
589                         cf_log_err(cf_sectiontoitem(cs), "You must supply a user name to enable status_check=request");
590                         goto error;
591                 }
592
593                 if ((home->type == HOME_TYPE_AUTH) &&
594                     !home->ping_user_password) {
595                         cf_log_err(cf_sectiontoitem(cs), "You must supply a password to enable status_check=request");
596                         goto error;
597                 }
598         }
599
600         home->proto = IPPROTO_UDP;
601 #ifdef WITH_TCP
602         if (hs_proto) {
603                 if (strcmp(hs_proto, "udp") == 0) {
604                         hs_proto = NULL;
605                         
606                 } else if (strcmp(hs_proto, "tcp") == 0) {
607                         hs_proto = NULL;
608                         home->proto = IPPROTO_TCP;
609                         
610                         if (home->ping_check != HOME_PING_CHECK_NONE) {
611                                 cf_log_err(cf_sectiontoitem(cs),
612                                            "Only 'status_check = none' is allowed for home servers with 'proto = tcp'");
613                                 goto error;
614                         }
615
616                 } else {
617                         cf_log_err(cf_sectiontoitem(cs),
618                                    "Unknown proto \"%s\".", hs_proto);
619                         goto error;
620                 }
621         }
622 #endif
623
624         if (!home->server &&
625             rbtree_finddata(home_servers_byaddr, home)) {
626                 cf_log_err(cf_sectiontoitem(cs), "Duplicate home server");
627                 goto error;
628         }
629
630         /*
631          *      Check the TLS configuration.
632          */
633         tls = cf_section_sub_find(cs, "tls");
634
635         /*
636          *      If the home is a virtual server, don't look up source IP.
637          */
638         if (!home->server) {
639                 rad_assert(home->ipaddr.af != AF_UNSPEC);
640
641                 /*
642                  *      Otherwise look up the source IP using the same
643                  *      address family as the destination IP.
644                  */
645                 if (hs_srcipaddr) {
646                         if (ip_hton(hs_srcipaddr, home->ipaddr.af, &home->src_ipaddr) < 0) {
647                                 cf_log_err(cf_sectiontoitem(cs), "Failed parsing src_ipaddr");
648                                 goto error;
649                         }
650                         
651                 } else {
652                         /*
653                          *      Source isn't specified: Source is
654                          *      the correct address family, but all zeros.
655                          */
656                         memset(&home->src_ipaddr, 0, sizeof(home->src_ipaddr));
657                         home->src_ipaddr.af = home->ipaddr.af;
658                 }
659
660                 if (tls && (home->proto != IPPROTO_TCP)) {
661                         cf_log_err(cf_sectiontoitem(cs), "TLS transport is not available for UDP sockets.");
662                         goto error;
663                 }
664
665 #ifndef WITH_TLS
666
667                 if (tls) {
668                         cf_log_err(cf_sectiontoitem(cs), "TLS transport is not available in this executable.");
669                         goto error;
670                 }
671 #else
672                 /*
673                  *      Parse the SSL client configuration.
674                  */
675                 if (tls) {
676                         home->tls = tls_client_conf_parse(tls);
677                         if (!home->tls) {
678                                 goto error;
679                         }
680                 }
681 #endif
682
683         } else if (tls) {
684                 cf_log_err(cf_sectiontoitem(cs), "Virtual home_servers cannot have a \"tls\" subsection");
685                 goto error;
686         }
687
688         /*
689          *      Make sure that this is set.
690          */
691         if (home->src_ipaddr.af == AF_UNSPEC) {
692                 home->src_ipaddr.af = home->ipaddr.af;
693         }
694
695         hs_srcipaddr = NULL;
696
697         if (rbtree_finddata(home_servers_byname, home) != NULL) {
698                 cf_log_err(cf_sectiontoitem(cs),
699                            "Duplicate home server name %s.", name2);
700                 goto error;
701         }
702
703         if (!home->server &&
704             (rbtree_finddata(home_servers_byaddr, home) != NULL)) {
705                 cf_log_err(cf_sectiontoitem(cs),
706                            "Duplicate home server IP %s.", name2);
707                 goto error;
708         }
709
710         if (!rbtree_insert(home_servers_byname, home)) {
711                 cf_log_err(cf_sectiontoitem(cs),
712                            "Internal error %d adding home server %s.",
713                            __LINE__, name2);
714                 goto error;
715         }
716
717         if (!home->server &&
718             !rbtree_insert(home_servers_byaddr, home)) {
719                 rbtree_deletebydata(home_servers_byname, home);
720                 cf_log_err(cf_sectiontoitem(cs),
721                            "Internal error %d adding home server %s.",
722                            __LINE__, name2);
723                 goto error;
724         }
725
726 #ifdef WITH_STATS
727         home->number = home_server_max_number++;
728         if (!rbtree_insert(home_servers_bynumber, home)) {
729                 rbtree_deletebydata(home_servers_byname, home);
730                 if (home->ipaddr.af != AF_UNSPEC) {
731                         rbtree_deletebydata(home_servers_byname, home);
732                 }
733                 cf_log_err(cf_sectiontoitem(cs),
734                            "Internal error %d adding home server %s.",
735                            __LINE__, name2);
736                 goto error;
737         }
738 #endif
739
740         if (home->max_outstanding < 8) home->max_outstanding = 8;
741         if (home->max_outstanding > 65536*16) home->max_outstanding = 65536*16;
742
743         if (home->ping_interval < 6) home->ping_interval = 6;
744         if (home->ping_interval > 120) home->ping_interval = 120;
745
746         if (home->response_window < 1) home->response_window = 1;
747         if (home->response_window > 60) home->response_window = 60;
748         if (home->response_window > mainconfig.max_request_time) home->response_window = mainconfig.max_request_time;
749
750         if (home->zombie_period < 1) home->zombie_period = 1;
751         if (home->zombie_period > 120) home->zombie_period = 120;
752
753         if (home->zombie_period < home->response_window) {
754                 home->zombie_period = home->response_window;
755         }
756
757         if (home->num_pings_to_alive < 3) home->num_pings_to_alive = 3;
758         if (home->num_pings_to_alive > 10) home->num_pings_to_alive = 10;
759
760         if (home->ping_timeout < 3) home->ping_timeout = 3;
761         if (home->ping_timeout > 10) home->ping_timeout = 10;
762
763         if (home->revive_interval < 60) home->revive_interval = 60;
764         if (home->revive_interval > 3600) home->revive_interval = 3600;
765
766 #ifdef WITH_COA
767         if (home->coa_irt < 1) home->coa_irt = 1;
768         if (home->coa_irt > 5) home->coa_irt = 5;
769
770         if (home->coa_mrc < 0) home->coa_mrc = 0;
771         if (home->coa_mrc > 20 ) home->coa_mrc = 20;
772
773         if (home->coa_mrt < 0) home->coa_mrt = 0;
774         if (home->coa_mrt > 30 ) home->coa_mrt = 30;
775
776         if (home->coa_mrd < 5) home->coa_mrd = 5;
777         if (home->coa_mrd > 60 ) home->coa_mrd = 60;
778 #endif
779
780         if (home->limit.max_connections > 1024) home->limit.max_connections = 1024;
781
782 #ifdef WITH_TCP
783         /*
784          *      UDP sockets can't be connection limited.
785          */
786         if (home->proto != IPPROTO_TCP) home->limit.max_connections = 0;
787 #endif
788
789         if ((home->limit.idle_timeout > 0) && (home->limit.idle_timeout < 5))
790                 home->limit.idle_timeout = 5;
791         if ((home->limit.lifetime > 0) && (home->limit.lifetime < 5))
792                 home->limit.lifetime = 5;
793         if ((home->limit.lifetime > 0) && (home->limit.idle_timeout > home->limit.lifetime))
794                 home->limit.idle_timeout = 0;
795
796         tls = cf_item_parent(cf_sectiontoitem(cs));
797         if (strcmp(cf_section_name1(tls), "server") == 0) {
798                 home->parent_server = cf_section_name2(tls);
799         }
800
801         if (dual) {
802                 home_server *home2 = rad_malloc(sizeof(*home2));
803
804                 memcpy(home2, home, sizeof(*home2));
805
806                 home2->type = HOME_TYPE_ACCT;
807                 home2->port++;
808                 home2->ping_user_password = NULL;
809                 home2->cs = cs;
810                 home2->parent_server = home->parent_server;
811
812                 if (!rbtree_insert(home_servers_byname, home2)) {
813                         cf_log_err(cf_sectiontoitem(cs),
814                                    "Internal error %d adding home server %s.",
815                                    __LINE__, name2);
816                         free(home2);
817                         return 0;
818                 }
819                 
820                 if (!home->server &&
821                     !rbtree_insert(home_servers_byaddr, home2)) {
822                         rbtree_deletebydata(home_servers_byname, home2);
823                         cf_log_err(cf_sectiontoitem(cs),
824                                    "Internal error %d adding home server %s.",
825                                    __LINE__, name2);
826                         free(home2);
827                         return 0;
828                 }
829
830 #ifdef WITH_STATS
831                 home2->number = home_server_max_number++;
832                 if (!rbtree_insert(home_servers_bynumber, home2)) {
833                         rbtree_deletebydata(home_servers_byname, home2);
834                         if (!home2->server) {
835                                 rbtree_deletebydata(home_servers_byname, home2);
836                         }
837                         cf_log_err(cf_sectiontoitem(cs),
838                                    "Internal error %d adding home server %s.",
839                                    __LINE__, name2);
840                         free(home2);
841                         return 0;
842                 }
843 #endif
844         }
845
846         /*
847          *      Mark it as already processed
848          */
849         cf_data_add(cs, "home_server", null_free, null_free);
850
851         return 1;
852 }
853
854
855 static home_pool_t *server_pool_alloc(const char *name, home_pool_type_t type,
856                                       int server_type, int num_home_servers)
857 {
858         home_pool_t *pool;
859
860         pool = rad_malloc(sizeof(*pool) + (sizeof(pool->servers[0]) *
861                                            num_home_servers));
862         if (!pool) return NULL; /* just for pairanoia */
863         
864         memset(pool, 0, sizeof(*pool) + (sizeof(pool->servers[0]) *
865                                          num_home_servers));
866
867         pool->name = name;
868         pool->type = type;
869         pool->server_type = server_type;
870         pool->num_home_servers = num_home_servers;
871
872         return pool;
873 }
874
875 static int pool_check_home_server(realm_config_t *rc, CONF_PAIR *cp,
876                                   const char *name, int server_type,
877                                   home_server **phome)
878 {
879         home_server myhome, *home;
880         CONF_SECTION *server_cs;
881
882         if (!name) {
883                 cf_log_err(cf_pairtoitem(cp),
884                            "No value given for home_server.");
885                 return 0;
886         }
887
888         myhome.name = name;
889         myhome.type = server_type;
890         home = rbtree_finddata(home_servers_byname, &myhome);
891         if (home) {
892                 *phome = home;
893                 return 1;
894         }
895         
896         server_cs = cf_section_sub_find_name2(rc->cs, "home_server", name);
897         if (!server_cs) {
898                 cf_log_err(cf_pairtoitem(cp),
899                            "Unknown home_server \"%s\".", name);
900                 return 0;
901         }
902         
903         home = rbtree_finddata(home_servers_byname, &myhome);
904         if (!home) {
905                 cf_log_err(cf_pairtoitem(cp),
906                            "Internal error %d adding home server \"%s\".",
907                            __LINE__, name);
908                 return 0;
909         }
910
911         *phome = home;
912         return 1;
913 }
914
915
916 static int server_pool_add(realm_config_t *rc,
917                            CONF_SECTION *cs, int server_type, int do_print)
918 {
919         const char *name2;
920         home_pool_t *pool = NULL;
921         const char *value;
922         CONF_PAIR *cp;
923         int num_home_servers;
924         home_server *home;
925
926         name2 = cf_section_name1(cs);
927         if (!name2 || ((strcasecmp(name2, "server_pool") != 0) &&
928                        (strcasecmp(name2, "home_server_pool") != 0))) {
929                 cf_log_err(cf_sectiontoitem(cs),
930                            "Section is not a home_server_pool.");
931                 return 0;
932         }
933
934         name2 = cf_section_name2(cs);
935         if (!name2) {
936                 cf_log_err(cf_sectiontoitem(cs),
937                            "Server pool section is missing a name.");
938                 return 0;
939         }
940
941         /*
942          *      Count the home servers and initalize them.
943          */
944         num_home_servers = 0;
945         for (cp = cf_pair_find(cs, "home_server");
946              cp != NULL;
947              cp = cf_pair_find_next(cs, cp, "home_server")) {
948                 num_home_servers++;
949
950                 if (!pool_check_home_server(rc, cp, cf_pair_value(cp),
951                                             server_type, &home)) {
952                         return 0;
953                 }
954         }
955
956         if (num_home_servers == 0) {
957                 cf_log_err(cf_sectiontoitem(cs),
958                            "No home servers defined in pool %s",
959                            name2);
960                 goto error;
961         }
962
963         pool = server_pool_alloc(name2, HOME_POOL_FAIL_OVER, server_type,
964                                  num_home_servers);
965         pool->cs = cs;
966
967
968         /*
969          *      Fallback servers must be defined, and must be
970          *      virtual servers.
971          */
972         cp = cf_pair_find(cs, "fallback");
973         if (cp) {
974 #ifdef WITH_COA
975                 if (server_type == HOME_TYPE_COA) {
976                         cf_log_err(cf_sectiontoitem(cs), "Home server pools of type \"coa\" cannot have a fallback virtual server.");
977                         goto error;
978                 }
979 #endif
980
981                 if (!pool_check_home_server(rc, cp, cf_pair_value(cp),
982                                             server_type, &pool->fallback)) {
983                         
984                         goto error;
985                 }
986
987                 if (!pool->fallback->server) {
988                         cf_log_err(cf_sectiontoitem(cs), "Fallback home_server %s does NOT contain a virtual_server directive.", pool->fallback->name);
989                         goto error;
990                 }
991         }
992
993         if (do_print) cf_log_info(cs, " home_server_pool %s {", name2);
994
995         cp = cf_pair_find(cs, "type");
996         if (cp) {
997                 static FR_NAME_NUMBER pool_types[] = {
998                         { "load-balance", HOME_POOL_LOAD_BALANCE },
999                         { "fail-over", HOME_POOL_FAIL_OVER },
1000                         { "round_robin", HOME_POOL_LOAD_BALANCE },
1001                         { "fail_over", HOME_POOL_FAIL_OVER },
1002                         { "client-balance", HOME_POOL_CLIENT_BALANCE },
1003                         { "client-port-balance", HOME_POOL_CLIENT_PORT_BALANCE },
1004                         { "keyed-balance", HOME_POOL_KEYED_BALANCE },
1005                         { NULL, 0 }
1006                 };
1007
1008                 value = cf_pair_value(cp);
1009                 if (!value) {
1010                         cf_log_err(cf_pairtoitem(cp),
1011                                    "No value given for type.");
1012                         goto error;
1013                 }
1014
1015                 pool->type = fr_str2int(pool_types, value, 0);
1016                 if (!pool->type) {
1017                         cf_log_err(cf_pairtoitem(cp),
1018                                    "Unknown type \"%s\".",
1019                                    value);
1020                         goto error;
1021                 }
1022
1023                 if (do_print) cf_log_info(cs, "\ttype = %s", value);
1024         }
1025
1026         cp = cf_pair_find(cs, "virtual_server");
1027         if (cp) {
1028                 pool->virtual_server = cf_pair_value(cp);               
1029                 if (!pool->virtual_server) {
1030                         cf_log_err(cf_pairtoitem(cp), "No value given for virtual_server");
1031                         goto error;
1032                 }
1033
1034                 if (do_print) {
1035                         cf_log_info(cs, "\tvirtual_server = %s", pool->virtual_server);
1036                 }
1037
1038                 if (!cf_section_sub_find_name2(rc->cs, "server",
1039                                                pool->virtual_server)) {
1040                         cf_log_err(cf_pairtoitem(cp), "No such server %s",
1041                                    pool->virtual_server);
1042                         goto error;
1043                 }
1044
1045         }
1046
1047         num_home_servers = 0;
1048         for (cp = cf_pair_find(cs, "home_server");
1049              cp != NULL;
1050              cp = cf_pair_find_next(cs, cp, "home_server")) {
1051                 home_server myhome;
1052
1053                 value = cf_pair_value(cp);
1054
1055                 memset(&myhome, 0, sizeof(myhome));
1056                 myhome.name = value;
1057                 myhome.type = server_type;
1058
1059                 home = rbtree_finddata(home_servers_byname, &myhome);
1060                 if (!home) {
1061                         DEBUG2("Internal sanity check failed");
1062                         goto error;
1063                 }
1064
1065                 if (0) {
1066                         DEBUG2("Warning: Duplicate home server %s in server pool %s", home->name, pool->name);
1067                         continue;
1068                 }
1069
1070                 if (do_print) cf_log_info(cs, "\thome_server = %s", home->name);
1071                 pool->servers[num_home_servers++] = home;
1072         } /* loop over home_server's */
1073
1074         if (pool->fallback && do_print) {
1075                 cf_log_info(cs, "\tfallback = %s", pool->fallback->name);
1076         }
1077
1078         if (!rbtree_insert(home_pools_byname, pool)) {
1079                 rad_assert("Internal sanity check failed");
1080                 goto error;
1081         }
1082
1083         if (do_print) cf_log_info(cs, " }");
1084
1085         cf_data_add(cs, "home_server_pool", pool, free);
1086
1087         rad_assert(pool->server_type != 0);
1088
1089         return 1;
1090
1091  error:
1092         if (do_print) cf_log_info(cs, " }");
1093         free(pool);
1094         return 0;
1095 }
1096 #endif
1097
1098 static int old_server_add(realm_config_t *rc, CONF_SECTION *cs,
1099                           const char *realm,
1100                           const char *name, const char *secret,
1101                           home_pool_type_t ldflag, home_pool_t **pool_p,
1102                           int type, const char *server)
1103 {
1104 #ifdef WITH_PROXY
1105         int i, insert_point, num_home_servers;
1106         home_server myhome, *home;
1107         home_pool_t mypool, *pool;
1108         CONF_SECTION *subcs;
1109 #else
1110         rc = rc;                /* -Wunused */
1111         realm = realm;
1112         secret = secret;
1113         ldflag = ldflag;
1114         type = type;
1115         server = server;
1116 #endif
1117
1118         /*
1119          *      LOCAL realms get sanity checked, and nothing else happens.
1120          */
1121         if (strcmp(name, "LOCAL") == 0) {
1122                 if (*pool_p) {
1123                         cf_log_err(cf_sectiontoitem(cs), "Realm \"%s\" cannot be both LOCAL and remote", name);
1124                         return 0;
1125                 }
1126                 return 1;
1127         }
1128
1129 #ifndef WITH_PROXY
1130         return 0;               /* Not proxying.  Can't do non-LOCAL realms */
1131
1132 #else
1133         mypool.name = realm;
1134         mypool.server_type = type;
1135         pool = rbtree_finddata(home_pools_byname, &mypool);
1136         if (pool) {
1137                 if (pool->type != ldflag) {
1138                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent ldflag for server pool \"%s\"", name);
1139                         return 0;
1140                 }
1141
1142                 if (pool->server_type != type) {
1143                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent home server type for server pool \"%s\"", name);
1144                         return 0;
1145                 }
1146         }
1147
1148         myhome.name = name;
1149         myhome.type = type;
1150         home = rbtree_finddata(home_servers_byname, &myhome);
1151         if (home) {
1152                 if (secret && (strcmp(home->secret, secret) != 0)) {
1153                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent shared secret for home server \"%s\"", name);
1154                         return 0;
1155                 }
1156
1157                 if (home->type != type) {
1158                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent type for home server \"%s\"", name);
1159                         return 0;
1160                 }
1161
1162                 /*
1163                  *      See if the home server is already listed
1164                  *      in the pool.  If so, do nothing else.
1165                  */
1166                 if (pool) for (i = 0; i < pool->num_home_servers; i++) {
1167                         if (pool->servers[i] == home) {
1168                                 return 1;
1169                         }
1170                 }
1171         }
1172
1173         /*
1174          *      If we do have a pool, check that there is room to
1175          *      insert the home server we've found, or the one that we
1176          *      create here.
1177          *
1178          *      Note that we insert it into the LAST available
1179          *      position, in order to maintain the same order as in
1180          *      the configuration files.
1181          */
1182         insert_point = -1;
1183         if (pool) {
1184                 for (i = pool->num_home_servers - 1; i >= 0; i--) {
1185                         if (pool->servers[i]) break;
1186
1187                         if (!pool->servers[i]) {
1188                                 insert_point = i;
1189                         }
1190                 }
1191
1192                 if (insert_point < 0) {
1193                         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);
1194                         return 0;
1195                 }
1196         }
1197
1198         /*
1199          *      No home server, allocate one.
1200          */
1201         if (!home) {
1202                 const char *p;
1203                 char *q;
1204
1205                 home = rad_malloc(sizeof(*home));
1206                 memset(home, 0, sizeof(*home));
1207
1208                 home->name = name;
1209                 home->hostname = name;
1210                 home->type = type;
1211                 home->secret = secret;
1212                 home->cs = cs;
1213                 home->proto = IPPROTO_UDP;
1214
1215                 p = strchr(name, ':');
1216                 if (!p) {
1217                         if (type == HOME_TYPE_AUTH) {
1218                                 home->port = PW_AUTH_UDP_PORT;
1219                         } else {
1220                                 home->port = PW_ACCT_UDP_PORT;
1221                         }
1222
1223                         p = name;
1224                         q = NULL;
1225
1226                 } else if (p == name) {
1227                                 cf_log_err(cf_sectiontoitem(cs),
1228                                            "Invalid hostname %s.",
1229                                            name);
1230                                 free(home);
1231                                 return 0;
1232
1233                 } else {
1234                         home->port = atoi(p + 1);
1235                         if ((home->port == 0) || (home->port > 65535)) {
1236                                 cf_log_err(cf_sectiontoitem(cs),
1237                                            "Invalid port %s.",
1238                                            p + 1);
1239                                 free(home);
1240                                 return 0;
1241                         }
1242
1243                         q = rad_malloc((p - name) + 1);
1244                         memcpy(q, name, (p - name));
1245                         q[p - name] = '\0';
1246                         p = q;
1247                 }
1248
1249                 if (!server) {
1250                         if (ip_hton(p, AF_UNSPEC, &home->ipaddr) < 0) {
1251                                 cf_log_err(cf_sectiontoitem(cs),
1252                                            "Failed looking up hostname %s.",
1253                                            p);
1254                                 free(home);
1255                                 free(q);
1256                                 return 0;
1257                         }
1258                         home->src_ipaddr.af = home->ipaddr.af;
1259                 } else {
1260                         home->ipaddr.af = AF_UNSPEC;
1261                         home->server = server;
1262                 }
1263                 free(q);
1264
1265                 /*
1266                  *      Use the old-style configuration.
1267                  */
1268                 home->max_outstanding = 65535*16;
1269                 home->zombie_period = rc->retry_delay * rc->retry_count;
1270                 if (home->zombie_period == 0) home->zombie_period =30;
1271                 home->response_window = home->zombie_period - 1;
1272
1273                 home->ping_check = HOME_PING_CHECK_NONE;
1274
1275                 home->revive_interval = rc->dead_time;
1276
1277                 if (rbtree_finddata(home_servers_byaddr, home)) {
1278                         cf_log_err(cf_sectiontoitem(cs), "Home server %s has the same IP address and/or port as another home server.", name);
1279                         free(home);
1280                         return 0;
1281                 }
1282
1283                 if (!rbtree_insert(home_servers_byname, home)) {
1284                         cf_log_err(cf_sectiontoitem(cs), "Internal error %d adding home server %s.", __LINE__, name);
1285                         free(home);
1286                         return 0;
1287                 }
1288
1289                 if (!rbtree_insert(home_servers_byaddr, home)) {
1290                         rbtree_deletebydata(home_servers_byname, home);
1291                         cf_log_err(cf_sectiontoitem(cs), "Internal error %d adding home server %s.", __LINE__, name);
1292                         free(home);
1293                         return 0;
1294                 }
1295
1296 #ifdef WITH_STATS
1297                 home->number = home_server_max_number++;
1298                 if (!rbtree_insert(home_servers_bynumber, home)) {
1299                         rbtree_deletebydata(home_servers_byname, home);
1300                         if (home->ipaddr.af != AF_UNSPEC) {
1301                                 rbtree_deletebydata(home_servers_byname, home);
1302                         }
1303                         cf_log_err(cf_sectiontoitem(cs),
1304                                    "Internal error %d adding home server %s.",
1305                                    __LINE__, name);
1306                         free(home);
1307                         return 0;
1308                 }
1309 #endif
1310         }
1311
1312         /*
1313          *      We now have a home server, see if we can insert it
1314          *      into pre-existing pool.
1315          */
1316         if (insert_point >= 0) {
1317                 rad_assert(pool != NULL);
1318                 pool->servers[insert_point] = home;
1319                 return 1;
1320         }
1321
1322         rad_assert(pool == NULL);
1323         rad_assert(home != NULL);
1324
1325         /*
1326          *      Count the old-style realms of this name.
1327          */
1328         num_home_servers = 0;
1329         for (subcs = cf_section_find_next(cs, NULL, "realm");
1330              subcs != NULL;
1331              subcs = cf_section_find_next(cs, subcs, "realm")) {
1332                 const char *this = cf_section_name2(subcs);
1333
1334                 if (!this || (strcmp(this, realm) != 0)) continue;
1335                 num_home_servers++;
1336         }
1337
1338         if (num_home_servers == 0) {
1339                 cf_log_err(cf_sectiontoitem(cs), "Internal error counting pools for home server %s.", name);
1340                 free(home);
1341                 return 0;
1342         }
1343
1344         pool = server_pool_alloc(realm, ldflag, type, num_home_servers);
1345         pool->cs = cs;
1346
1347         pool->servers[0] = home;
1348
1349         if (!rbtree_insert(home_pools_byname, pool)) {
1350                 rad_assert("Internal sanity check failed");
1351                 return 0;
1352         }
1353
1354         *pool_p = pool;
1355
1356         return 1;
1357 #endif
1358 }
1359
1360 static int old_realm_config(realm_config_t *rc, CONF_SECTION *cs, REALM *r)
1361 {
1362         const char *host;
1363         const char *secret = NULL;
1364         home_pool_type_t ldflag;
1365         CONF_PAIR *cp;
1366
1367         cp = cf_pair_find(cs, "ldflag");
1368         ldflag = HOME_POOL_FAIL_OVER;
1369         if (cp) {
1370                 host = cf_pair_value(cp);
1371                 if (!host) {
1372                         cf_log_err(cf_pairtoitem(cp), "No value specified for ldflag");
1373                         return 0;
1374                 }
1375
1376                 if (strcasecmp(host, "fail_over") == 0) {
1377                         cf_log_info(cs, "\tldflag = fail_over");
1378                         
1379                 } else if (strcasecmp(host, "round_robin") == 0) {
1380                         ldflag = HOME_POOL_LOAD_BALANCE;
1381                         cf_log_info(cs, "\tldflag = round_robin");
1382                         
1383                 } else {
1384                         cf_log_err(cf_sectiontoitem(cs), "Unknown value \"%s\" for ldflag", host);
1385                         return 0;
1386                 }
1387         } /* else don't print it. */
1388
1389         /*
1390          *      Allow old-style if it doesn't exist, or if it exists and
1391          *      it's LOCAL.
1392          */
1393         cp = cf_pair_find(cs, "authhost");
1394         if (cp) {
1395                 host = cf_pair_value(cp);
1396                 if (!host) {
1397                         cf_log_err(cf_pairtoitem(cp), "No value specified for authhost");
1398                         return 0;
1399                 }
1400
1401                 if (strcmp(host, "LOCAL") != 0) {
1402                         cp = cf_pair_find(cs, "secret");
1403                         if (!cp) {
1404                                 cf_log_err(cf_sectiontoitem(cs), "No shared secret supplied for realm: %s", r->name);
1405                                 return 0;
1406                         }
1407
1408                         secret = cf_pair_value(cp);
1409                         if (!secret) {
1410                                 cf_log_err(cf_pairtoitem(cp), "No value specified for secret");
1411                                 return 0;
1412                         }
1413                 }
1414                         
1415                 cf_log_info(cs, "\tauthhost = %s",  host);
1416
1417                 if (!old_server_add(rc, cs, r->name, host, secret, ldflag,
1418                                     &r->auth_pool, HOME_TYPE_AUTH, NULL)) {
1419                         return 0;
1420                 }
1421         }
1422
1423         cp = cf_pair_find(cs, "accthost");
1424         if (cp) {
1425                 host = cf_pair_value(cp);
1426                 if (!host) {
1427                         cf_log_err(cf_pairtoitem(cp), "No value specified for accthost");
1428                         return 0;
1429                 }
1430
1431                 /*
1432                  *      Don't look for a secret again if it was found
1433                  *      above.
1434                  */
1435                 if ((strcmp(host, "LOCAL") != 0) && !secret) {
1436                         cp = cf_pair_find(cs, "secret");
1437                         if (!cp) {
1438                                 cf_log_err(cf_sectiontoitem(cs), "No shared secret supplied for realm: %s", r->name);
1439                                 return 0;
1440                         }
1441                         
1442                         secret = cf_pair_value(cp);
1443                         if (!secret) {
1444                                 cf_log_err(cf_pairtoitem(cp), "No value specified for secret");
1445                                 return 0;
1446                         }
1447                 }
1448                 
1449                 cf_log_info(cs, "\taccthost = %s", host);
1450
1451                 if (!old_server_add(rc, cs, r->name, host, secret, ldflag,
1452                                     &r->acct_pool, HOME_TYPE_ACCT, NULL)) {
1453                         return 0;
1454                 }
1455         }
1456
1457         cp = cf_pair_find(cs, "virtual_server");
1458         if (cp) {
1459                 host = cf_pair_value(cp);
1460                 if (!host) {
1461                         cf_log_err(cf_pairtoitem(cp), "No value specified for virtual_server");
1462                         return 0;
1463                 }
1464
1465                 cf_log_info(cs, "\tvirtual_server = %s", host);
1466
1467                 if (!old_server_add(rc, cs, r->name, host, "", ldflag,
1468                                     &r->auth_pool, HOME_TYPE_AUTH, host)) {
1469                         return 0;
1470                 }
1471                 if (!old_server_add(rc, cs, r->name, host, "", ldflag,
1472                                     &r->acct_pool, HOME_TYPE_ACCT, host)) {
1473                         return 0;
1474                 }
1475         }
1476
1477         if (secret) cf_log_info(cs, "\tsecret = %s", secret);
1478
1479         return 1;
1480
1481 }
1482
1483
1484 #ifdef WITH_PROXY
1485 static int add_pool_to_realm(realm_config_t *rc, CONF_SECTION *cs,
1486                              const char *name, home_pool_t **dest,
1487                              int server_type, int do_print)
1488 {
1489         home_pool_t mypool, *pool;
1490
1491         mypool.name = name;
1492         mypool.server_type = server_type;
1493
1494         pool = rbtree_finddata(home_pools_byname, &mypool);
1495         if (!pool) {
1496                 CONF_SECTION *pool_cs;
1497
1498                 pool_cs = cf_section_sub_find_name2(rc->cs,
1499                                                     "home_server_pool",
1500                                                     name);
1501                 if (!pool_cs) {
1502                         pool_cs = cf_section_sub_find_name2(rc->cs,
1503                                                             "server_pool",
1504                                                             name);
1505                 }
1506                 if (!pool_cs) {
1507                         cf_log_err(cf_sectiontoitem(cs), "Failed to find home_server_pool \"%s\"", name);
1508                         return 0;
1509                 }
1510
1511                 if (!server_pool_add(rc, pool_cs, server_type, do_print)) {
1512                         return 0;
1513                 }
1514
1515                 pool = rbtree_finddata(home_pools_byname, &mypool);
1516                 if (!pool) {
1517                         radlog(L_ERR, "Internal sanity check failed in add_pool_to_realm");
1518                         return 0;
1519                 }
1520         }
1521
1522         if (pool->server_type != server_type) {
1523                 cf_log_err(cf_sectiontoitem(cs), "Incompatible home_server_pool \"%s\" (mixed auth_pool / acct_pool)", name);
1524                 return 0;
1525         }
1526
1527         *dest = pool;
1528
1529         return 1;
1530 }
1531 #endif
1532
1533
1534 static int realm_add(realm_config_t *rc, CONF_SECTION *cs)
1535 {
1536         const char *name2;
1537         REALM *r = NULL;
1538         CONF_PAIR *cp;
1539 #ifdef WITH_PROXY
1540         home_pool_t *auth_pool, *acct_pool;
1541         const char *auth_pool_name, *acct_pool_name;
1542 #ifdef WITH_COA
1543         const char *coa_pool_name;
1544         home_pool_t *coa_pool;
1545 #endif
1546 #endif
1547
1548         name2 = cf_section_name1(cs);
1549         if (!name2 || (strcasecmp(name2, "realm") != 0)) {
1550                 cf_log_err(cf_sectiontoitem(cs), "Section is not a realm.");
1551                 return 0;
1552         }
1553
1554         name2 = cf_section_name2(cs);
1555         if (!name2) {
1556                 cf_log_err(cf_sectiontoitem(cs), "Realm section is missing the realm name.");
1557                 return 0;
1558         }
1559
1560 #ifdef WITH_PROXY
1561         auth_pool = acct_pool = NULL;
1562         auth_pool_name = acct_pool_name = NULL;
1563 #ifdef WITH_COA
1564         coa_pool = NULL;
1565         coa_pool_name = NULL;
1566 #endif
1567
1568         /*
1569          *      Prefer new configuration to old one.
1570          */
1571         cp = cf_pair_find(cs, "pool");
1572         if (!cp) cp = cf_pair_find(cs, "home_server_pool");
1573         if (cp) auth_pool_name = cf_pair_value(cp);
1574         if (cp && auth_pool_name) {
1575                 acct_pool_name = auth_pool_name;
1576                 if (!add_pool_to_realm(rc, cs,
1577                                        auth_pool_name, &auth_pool,
1578                                        HOME_TYPE_AUTH, 1)) {
1579                         return 0;
1580                 }
1581                 if (!add_pool_to_realm(rc, cs,
1582                                        auth_pool_name, &acct_pool,
1583                                        HOME_TYPE_ACCT, 0)) {
1584                         return 0;
1585                 }
1586         }
1587
1588         cp = cf_pair_find(cs, "auth_pool");
1589         if (cp) auth_pool_name = cf_pair_value(cp);
1590         if (cp && auth_pool_name) {
1591                 if (auth_pool) {
1592                         cf_log_err(cf_sectiontoitem(cs), "Cannot use \"pool\" and \"auth_pool\" at the same time.");
1593                         return 0;
1594                 }
1595                 if (!add_pool_to_realm(rc, cs,
1596                                        auth_pool_name, &auth_pool,
1597                                        HOME_TYPE_AUTH, 1)) {
1598                         return 0;
1599                 }
1600         }
1601
1602         cp = cf_pair_find(cs, "acct_pool");
1603         if (cp) acct_pool_name = cf_pair_value(cp);
1604         if (cp && acct_pool_name) {
1605                 int do_print = TRUE;
1606
1607                 if (acct_pool) {
1608                         cf_log_err(cf_sectiontoitem(cs), "Cannot use \"pool\" and \"acct_pool\" at the same time.");
1609                         return 0;
1610                 }
1611
1612                 if (!auth_pool ||
1613                     (auth_pool_name &&
1614                      (strcmp(auth_pool_name, acct_pool_name) != 0))) {
1615                         do_print = TRUE;
1616                 }
1617
1618                 if (!add_pool_to_realm(rc, cs,
1619                                        acct_pool_name, &acct_pool,
1620                                        HOME_TYPE_ACCT, do_print)) {
1621                         return 0;
1622                 }
1623         }
1624
1625 #ifdef WITH_COA
1626         cp = cf_pair_find(cs, "coa_pool");
1627         if (cp) coa_pool_name = cf_pair_value(cp);
1628         if (cp && coa_pool_name) {
1629                 int do_print = TRUE;
1630
1631                 if (!add_pool_to_realm(rc, cs,
1632                                        coa_pool_name, &coa_pool,
1633                                        HOME_TYPE_COA, do_print)) {
1634                         return 0;
1635                 }
1636         }
1637 #endif
1638 #endif
1639
1640         cf_log_info(cs, " realm %s {", name2);
1641
1642 #ifdef WITH_PROXY
1643         /*
1644          *      The realm MAY already exist if it's an old-style realm.
1645          *      In that case, merge the old-style realm with this one.
1646          */
1647         r = realm_find2(name2);
1648         if (r && (strcmp(r->name, name2) == 0)) {
1649                 if (cf_pair_find(cs, "auth_pool") ||
1650                     cf_pair_find(cs, "acct_pool")) {
1651                         cf_log_err(cf_sectiontoitem(cs), "Duplicate realm \"%s\"", name2);
1652                         goto error;
1653                 }
1654
1655                 if (!old_realm_config(rc, cs, r)) {
1656                         goto error;
1657                 }
1658
1659                 cf_log_info(cs, " } # realm %s", name2);
1660                 return 1;
1661         }
1662 #endif
1663
1664 #ifdef HAVE_REGEX_H
1665         if (name2[0] == '~') {
1666                 int rcode;
1667                 regex_t reg;
1668                 
1669                 /*
1670                  *      Include substring matches.
1671                  */
1672                 rcode = regcomp(&reg, name2 + 1,
1673                                 REG_EXTENDED | REG_NOSUB | REG_ICASE);
1674                 if (rcode != 0) {
1675                         char buffer[256];
1676
1677                         regerror(rcode, &reg, buffer, sizeof(buffer));
1678
1679                         cf_log_err(cf_sectiontoitem(cs),
1680                                    "Invalid regex \"%s\": %s",
1681                                    name2 + 1, buffer);
1682                         goto error;
1683                 }
1684                 regfree(&reg);
1685         }
1686 #endif
1687
1688         r = rad_malloc(sizeof(*r));
1689         memset(r, 0, sizeof(*r));
1690
1691         r->name = name2;
1692         r->striprealm = 1;
1693 #ifdef WITH_PROXY
1694         r->auth_pool = auth_pool;
1695         r->acct_pool = acct_pool;
1696 #ifdef WITH_COA
1697         r->coa_pool = coa_pool;
1698 #endif
1699
1700         if (auth_pool_name &&
1701             (auth_pool_name == acct_pool_name)) { /* yes, ptr comparison */
1702                 cf_log_info(cs, "\tpool = %s", auth_pool_name);
1703         } else {
1704                 if (auth_pool_name) cf_log_info(cs, "\tauth_pool = %s", auth_pool_name);
1705                 if (acct_pool_name) cf_log_info(cs, "\tacct_pool = %s", acct_pool_name);
1706 #ifdef WITH_COA
1707                 if (coa_pool_name) cf_log_info(cs, "\tcoa_pool = %s", coa_pool_name);
1708 #endif
1709         }
1710 #endif
1711
1712         cp = cf_pair_find(cs, "nostrip");
1713         if (cp && (cf_pair_value(cp) == NULL)) {
1714                 r->striprealm = 0;
1715                 cf_log_info(cs, "\tnostrip");
1716         }
1717
1718         /*
1719          *      We're a new-style realm.  Complain if we see the old
1720          *      directives.
1721          */
1722         if (r->auth_pool || r->acct_pool) {
1723                 if (((cp = cf_pair_find(cs, "authhost")) != NULL) ||
1724                     ((cp = cf_pair_find(cs, "accthost")) != NULL) ||
1725                     ((cp = cf_pair_find(cs, "secret")) != NULL) ||
1726                     ((cp = cf_pair_find(cs, "ldflag")) != NULL)) {
1727                         DEBUG2W("Ignoring old-style configuration entry \"%s\" in realm \"%s\"", cf_pair_attr(cp), r->name);
1728                 }
1729
1730
1731                 /*
1732                  *      The realm MAY be an old-style realm, as there
1733                  *      was no auth_pool or acct_pool.  Double-check
1734                  *      it, just to be safe.
1735                  */
1736         } else if (!old_realm_config(rc, cs, r)) {
1737                 goto error;
1738         }
1739
1740 #ifdef HAVE_REGEX_H
1741         /*
1742          *      It's a regex.  Add it to a separate list.
1743          */
1744         if (name2[0] == '~') {
1745                 realm_regex_t *rr, **last;
1746
1747                 rr = rad_malloc(sizeof(*rr));
1748                 
1749                 last = &realms_regex;
1750                 while (*last) last = &((*last)->next);  /* O(N^2)... sue me. */
1751
1752                 r->name = name2;
1753                 rr->realm = r;
1754                 rr->next = NULL;
1755
1756                 *last = rr;
1757
1758                 cf_log_info(cs, " }");
1759                 return 1;
1760         }
1761 #endif
1762
1763         if (!rbtree_insert(realms_byname, r)) {
1764                 rad_assert("Internal sanity check failed");
1765                 goto error;
1766         }
1767
1768         cf_log_info(cs, " }");
1769
1770         return 1;
1771
1772  error:
1773         cf_log_info(cs, " } # realm %s", name2);
1774         free(r);
1775         return 0;
1776 }
1777
1778 #ifdef WITH_COA
1779 static const FR_NAME_NUMBER home_server_types[] = {
1780         { "auth", HOME_TYPE_AUTH },
1781         { "auth+acct", HOME_TYPE_AUTH },
1782         { "acct", HOME_TYPE_ACCT },
1783         { "coa", HOME_TYPE_COA },
1784         { NULL, 0 }
1785 };
1786
1787 static int pool_peek_type(CONF_SECTION *config, CONF_SECTION *cs)
1788 {
1789         int home;
1790         const char *name, *type;
1791         CONF_PAIR *cp;
1792         CONF_SECTION *server_cs;
1793
1794         cp = cf_pair_find(cs, "home_server");
1795         if (!cp) {
1796                 cf_log_err(cf_sectiontoitem(cs), "Pool does not contain a \"home_server\" entry");
1797                 return HOME_TYPE_INVALID;
1798         }
1799
1800         name = cf_pair_value(cp);
1801         if (!name) {
1802                 cf_log_err(cf_pairtoitem(cp), "home_server entry does not reference a home server");
1803                 return HOME_TYPE_INVALID;
1804         }
1805
1806         server_cs = cf_section_sub_find_name2(config, "home_server", name);
1807         if (!server_cs) {
1808                 cf_log_err(cf_pairtoitem(cp), "home_server \"%s\" does not exist", name);
1809                 return HOME_TYPE_INVALID;
1810         }
1811
1812         cp = cf_pair_find(server_cs, "type");
1813         if (!cp) {
1814                 cf_log_err(cf_sectiontoitem(server_cs), "home_server %s does not contain a \"type\" entry", name);
1815                 return HOME_TYPE_INVALID;
1816         }
1817
1818         type = cf_pair_value(cp);
1819         if (!type) {
1820                 cf_log_err(cf_sectiontoitem(server_cs), "home_server %s contains an empty \"type\" entry", name);
1821                 return HOME_TYPE_INVALID;
1822         }
1823
1824         home = fr_str2int(home_server_types, type, HOME_TYPE_INVALID);
1825         if (home == HOME_TYPE_INVALID) {
1826                 cf_log_err(cf_sectiontoitem(server_cs), "home_server %s contains an invalid \"type\" entry of value \"%s\"", name, type);
1827                 return HOME_TYPE_INVALID;
1828         }
1829
1830         return home;            /* 'cause we miss it so much */
1831 }
1832 #endif
1833
1834 int realms_init(CONF_SECTION *config)
1835 {
1836         CONF_SECTION *cs;
1837 #ifdef WITH_PROXY
1838         CONF_SECTION *server_cs;
1839 #endif
1840         realm_config_t *rc, *old_rc;
1841
1842         if (realms_byname) return 1;
1843
1844         realms_byname = rbtree_create(realm_name_cmp, free, 0);
1845         if (!realms_byname) {
1846                 realms_free();
1847                 return 0;
1848         }
1849
1850 #ifdef WITH_PROXY
1851         home_servers_byaddr = rbtree_create(home_server_addr_cmp, home_server_free, 0);
1852         if (!home_servers_byaddr) {
1853                 realms_free();
1854                 return 0;
1855         }
1856
1857         home_servers_byname = rbtree_create(home_server_name_cmp, NULL, 0);
1858         if (!home_servers_byname) {
1859                 realms_free();
1860                 return 0;
1861         }
1862
1863 #ifdef WITH_STATS
1864         home_servers_bynumber = rbtree_create(home_server_number_cmp, NULL, 0);
1865         if (!home_servers_bynumber) {
1866                 realms_free();
1867                 return 0;
1868         }
1869 #endif
1870
1871         home_pools_byname = rbtree_create(home_pool_name_cmp, NULL, 0);
1872         if (!home_pools_byname) {
1873                 realms_free();
1874                 return 0;
1875         }
1876 #endif
1877
1878         rc = rad_malloc(sizeof(*rc));
1879         memset(rc, 0, sizeof(*rc));
1880         rc->cs = config;
1881
1882 #ifdef WITH_PROXY
1883         cs = cf_subsection_find_next(config, NULL, "proxy");
1884         if (cs) {
1885                 if (cf_section_parse(cs, rc, proxy_config) < 0) {
1886                         radlog(L_ERR, "Failed parsing proxy section");
1887                         
1888                         free(rc);
1889                         realms_free();
1890                         return 0;
1891                 }
1892         } else {
1893                 rc->dead_time = DEAD_TIME;
1894                 rc->retry_count = RETRY_COUNT;
1895                 rc->retry_delay = RETRY_DELAY;
1896                 rc->fallback = 0;
1897                 rc->wake_all_if_all_dead= 0;
1898         }
1899
1900         for (cs = cf_subsection_find_next(config, NULL, "home_server");
1901              cs != NULL;
1902              cs = cf_subsection_find_next(config, cs, "home_server")) {
1903                 if (!home_server_add(rc, cs)) {
1904                         free(rc);
1905                         realms_free();
1906                         return 0;
1907                 }
1908         }
1909
1910         /*
1911          *      Loop over virtual servers to find homes which are
1912          *      defined in them.
1913          */
1914         for (server_cs = cf_subsection_find_next(config, NULL, "server");
1915              server_cs != NULL;
1916              server_cs = cf_subsection_find_next(config, server_cs, "server")) {
1917                 for (cs = cf_subsection_find_next(server_cs, NULL, "home_server");
1918                      cs != NULL;
1919                      cs = cf_subsection_find_next(server_cs, cs, "home_server")) {
1920                         if (!home_server_add(rc, cs)) {
1921                                 free(rc);
1922                                 realms_free();
1923                                 return 0;
1924                         }
1925                 }
1926         }
1927 #endif
1928
1929         for (cs = cf_subsection_find_next(config, NULL, "realm");
1930              cs != NULL;
1931              cs = cf_subsection_find_next(config, cs, "realm")) {
1932                 if (!realm_add(rc, cs)) {
1933                         free(rc);
1934                         realms_free();
1935                         return 0;
1936                 }
1937         }
1938
1939 #ifdef WITH_COA
1940         /*
1941          *      CoA pools aren't necessarily tied to realms.
1942          */
1943         for (cs = cf_subsection_find_next(config, NULL, "home_server_pool");
1944              cs != NULL;
1945              cs = cf_subsection_find_next(config, cs, "home_server_pool")) {
1946                 int type;
1947
1948                 /*
1949                  *      Pool was already loaded.
1950                  */
1951                 if (cf_data_find(cs, "home_server_pool")) continue;
1952
1953                 type = pool_peek_type(config, cs);
1954                 if (type == HOME_TYPE_INVALID) {
1955                         free(rc);
1956                         realms_free();
1957                         return 0;
1958                 }
1959
1960                 if (!server_pool_add(rc, cs, type, TRUE)) {
1961                         free(rc);
1962                         realms_free();
1963                         return 0;
1964                 }
1965         }
1966 #endif
1967
1968
1969 #ifdef WITH_PROXY
1970         xlat_register("home_server", xlat_home_server, NULL);
1971         xlat_register("home_server_pool", xlat_server_pool, NULL);
1972 #endif
1973
1974         /*
1975          *      Swap pointers atomically.
1976          */
1977         old_rc = realm_config;
1978         realm_config = rc;
1979         free(old_rc);
1980
1981         return 1;
1982 }
1983
1984 /*
1985  *      Find a realm where "name" might be the regex.
1986  */
1987 REALM *realm_find2(const char *name)
1988 {
1989         REALM myrealm;
1990         REALM *realm;
1991         
1992         if (!name) name = "NULL";
1993
1994         myrealm.name = name;
1995         realm = rbtree_finddata(realms_byname, &myrealm);
1996         if (realm) return realm;
1997
1998 #ifdef HAVE_REGEX_H
1999         if (realms_regex) {
2000                 realm_regex_t *this;
2001
2002                 for (this = realms_regex; this != NULL; this = this->next) {
2003                         if (strcmp(this->realm->name, name) == 0) {
2004                                 return this->realm;
2005                         }
2006                 }
2007         }
2008 #endif
2009
2010         /*
2011          *      Couldn't find a realm.  Look for DEFAULT.
2012          */
2013         myrealm.name = "DEFAULT";
2014         return rbtree_finddata(realms_byname, &myrealm);
2015 }
2016
2017
2018 /*
2019  *      Find a realm in the REALM list.
2020  */
2021 REALM *realm_find(const char *name)
2022 {
2023         REALM myrealm;
2024         REALM *realm;
2025         
2026         if (!name) name = "NULL";
2027
2028         myrealm.name = name;
2029         realm = rbtree_finddata(realms_byname, &myrealm);
2030         if (realm) return realm;
2031
2032 #ifdef HAVE_REGEX_H
2033         if (realms_regex) {
2034                 realm_regex_t *this;
2035
2036                 for (this = realms_regex; this != NULL; this = this->next) {
2037                         int compare;
2038                         regex_t reg;
2039
2040                         /*
2041                          *      Include substring matches.
2042                          */
2043                         if (regcomp(&reg, this->realm->name + 1,
2044                                     REG_EXTENDED | REG_NOSUB | REG_ICASE) != 0) {
2045                                 continue;
2046                         }
2047
2048                         compare = regexec(&reg, name, 0, NULL, 0);
2049                         regfree(&reg);
2050
2051                         if (compare == 0) return this->realm;
2052                 }
2053         }
2054 #endif
2055
2056         /*
2057          *      Couldn't find a realm.  Look for DEFAULT.
2058          */
2059         myrealm.name = "DEFAULT";
2060         return rbtree_finddata(realms_byname, &myrealm);
2061 }
2062
2063
2064 #ifdef WITH_PROXY
2065
2066 /*
2067  *      Allocate the proxy list if it doesn't already exist, and copy request
2068  *      VPs into it. Setup src/dst IP addresses based on home server, and
2069  *      calculate and add the message-authenticator.
2070  *
2071  *      This is a distinct function from home_server_ldb, as not all home_server
2072  *      lookups result in the *CURRENT* request being proxied,
2073  *      as in rlm_replicate, and this may trigger asserts elsewhere in the
2074  *      server.
2075  */
2076 void home_server_update_request(home_server *home, REQUEST *request)
2077 {
2078
2079         /*
2080          *      Allocate the proxy packet, only if it wasn't
2081          *      already allocated by a module.  This check is
2082          *      mainly to support the proxying of EAP-TTLS and
2083          *      EAP-PEAP tunneled requests.
2084          *
2085          *      In those cases, the EAP module creates a
2086          *      "fake" request, and recursively passes it
2087          *      through the authentication stage of the
2088          *      server.  The module then checks if the request
2089          *      was supposed to be proxied, and if so, creates
2090          *      a proxy packet from the TUNNELED request, and
2091          *      not from the EAP request outside of the
2092          *      tunnel.
2093          *
2094          *      The proxy then works like normal, except that
2095          *      the response packet is "eaten" by the EAP
2096          *      module, and encapsulated into an EAP packet.
2097          */
2098         if (!request->proxy) {
2099                 request->proxy = rad_alloc(request, TRUE);
2100                 if (!request->proxy) {
2101                         radlog(L_ERR, "no memory");
2102                         exit(1);
2103                 }
2104                 
2105                 /*
2106                  *      Copy the request, then look up name
2107                  *      and plain-text password in the copy.
2108                  *
2109                  *      Note that the User-Name attribute is
2110                  *      the *original* as sent over by the
2111                  *      client.  The Stripped-User-Name
2112                  *      attribute is the one hacked through
2113                  *      the 'hints' file.
2114                  */
2115                 request->proxy->vps =  paircopy(request->packet->vps);
2116         }
2117
2118         /*
2119          *      Update the various fields as appropriate.
2120          */
2121         request->proxy->src_ipaddr = home->src_ipaddr;
2122         request->proxy->src_port = 0;
2123         request->proxy->dst_ipaddr = home->ipaddr;
2124         request->proxy->dst_port = home->port;
2125         request->home_server = home;
2126
2127         /*
2128          *      Access-Requests have a Message-Authenticator added,
2129          *      unless one already exists.
2130          */
2131         if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2132             !pairfind(request->proxy->vps, PW_MESSAGE_AUTHENTICATOR, 0, TAG_ANY)) {
2133                 radius_pairmake(request, &request->proxy->vps,
2134                                 "Message-Authenticator", "0x00",
2135                                 T_OP_SET);
2136         }
2137 }
2138
2139 home_server *home_server_ldb(const char *realmname,
2140                              home_pool_t *pool, REQUEST *request)
2141 {
2142         int             start;
2143         int             count;
2144         home_server     *found = NULL;
2145         home_server     *zombie = NULL;
2146         VALUE_PAIR      *vp;
2147
2148         /*
2149          *      Determine how to pick choose the home server.
2150          */
2151         switch (pool->type) {
2152                 uint32_t hash;
2153
2154                 /*
2155                  *      For load-balancing by client IP address, we
2156                  *      pick a home server by hashing the client IP.
2157                  *
2158                  *      This isn't as even a load distribution as
2159                  *      tracking the State attribute, but it's better
2160                  *      than nothing.
2161                  */
2162         case HOME_POOL_CLIENT_BALANCE:
2163                 switch (request->packet->src_ipaddr.af) {
2164                 case AF_INET:
2165                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
2166                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
2167                         break;
2168                 case AF_INET6:
2169                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
2170                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
2171                         break;
2172                 default:
2173                         hash = 0;
2174                         break;
2175                 }
2176                 start = hash % pool->num_home_servers;
2177                 break;
2178
2179         case HOME_POOL_CLIENT_PORT_BALANCE:
2180                 switch (request->packet->src_ipaddr.af) {
2181                 case AF_INET:
2182                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
2183                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
2184                         break;
2185                 case AF_INET6:
2186                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
2187                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
2188                         break;
2189                 default:
2190                         hash = 0;
2191                         break;
2192                 }
2193                 fr_hash_update(&request->packet->src_port,
2194                                  sizeof(request->packet->src_port), hash);
2195                 start = hash % pool->num_home_servers;
2196                 break;
2197
2198         case HOME_POOL_KEYED_BALANCE:
2199                 if ((vp = pairfind(request->config_items, PW_LOAD_BALANCE_KEY, 0, TAG_ANY)) != NULL) {
2200                         hash = fr_hash(vp->vp_strvalue, vp->length);
2201                         start = hash % pool->num_home_servers;
2202                         break;
2203                 }
2204                 /* FALL-THROUGH */
2205                                 
2206         case HOME_POOL_LOAD_BALANCE:
2207         case HOME_POOL_FAIL_OVER:
2208                 start = 0;
2209                 break;
2210
2211         default:                /* this shouldn't happen... */
2212                 start = 0;
2213                 break;
2214
2215         }
2216
2217         /*
2218          *      Starting with the home server we chose, loop through
2219          *      all home servers.  If the current one is dead, skip
2220          *      it.  If it is too busy, skip it.
2221          *
2222          *      Otherwise, use it.
2223          */
2224         for (count = 0; count < pool->num_home_servers; count++) {
2225                 home_server *home = pool->servers[(start + count) % pool->num_home_servers];
2226
2227                 if (!home) continue;
2228
2229                 /*
2230                  *      Skip dead home servers.
2231                  *
2232                  *      Home servers that are unknown, alive, or zombie
2233                  *      are used for proxying.
2234                  */
2235                 if (home->state == HOME_STATE_IS_DEAD) {
2236                         continue;
2237                 }
2238
2239                 /*
2240                  *      This home server is too busy.  Choose another one.
2241                  */
2242                 if (home->currently_outstanding >= home->max_outstanding) {
2243                         continue;
2244                 }
2245
2246 #ifdef WITH_DETAIL
2247                 /*
2248                  *      We read the packet from a detail file, AND it
2249                  *      came from this server.  Don't re-proxy it
2250                  *      there.
2251                  */
2252                 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
2253                     (request->packet->code == PW_ACCOUNTING_REQUEST) &&
2254                     (fr_ipaddr_cmp(&home->ipaddr, &request->packet->src_ipaddr) == 0)) {
2255                         continue;
2256                 }
2257 #endif
2258
2259                 /*
2260                  *      Default virtual: ignore homes tied to a
2261                  *      virtual.
2262                  */
2263                 if (!request->server && home->parent_server) {
2264                         continue;
2265                 }
2266
2267                 /*
2268                  *      A virtual AND home is tied to virtual,
2269                  *      ignore ones which don't match.
2270                  */
2271                 if (request->server && home->parent_server &&
2272                     strcmp(request->server, home->parent_server) != 0) {
2273                         continue;
2274                 }
2275
2276                 /*
2277                  *      Allow request->server && !home->parent_server
2278                  *
2279                  *      i.e. virtuals can proxy to globally defined
2280                  *      homes.
2281                  */
2282
2283                 /*
2284                  *      It's zombie, so we remember the first zombie
2285                  *      we find, but we don't mark it as a "live"
2286                  *      server.
2287                  */
2288                 if (home->state == HOME_STATE_ZOMBIE) {
2289                         if (!zombie) zombie = home;
2290                         continue;
2291                 }
2292
2293                 /*
2294                  *      We've found the first "live" one.  Use that.
2295                  */
2296                 if (pool->type != HOME_POOL_LOAD_BALANCE) {
2297                         found = home;
2298                         break;
2299                 }
2300
2301                 /*
2302                  *      Otherwise we're doing some kind of load balancing.
2303                  *      If we haven't found one yet, pick this one.
2304                  */
2305                 if (!found) {
2306                         found = home;
2307                         continue;
2308                 }
2309
2310                 RDEBUG3("PROXY %s %d\t%s %d",
2311                        found->name, found->currently_outstanding,
2312                        home->name, home->currently_outstanding);
2313
2314                 /*
2315                  *      Prefer this server if it's less busy than the
2316                  *      one we had previously found.
2317                  */
2318                 if (home->currently_outstanding < found->currently_outstanding) {
2319                         RDEBUG3("PROXY Choosing %s: It's less busy than %s",
2320                                home->name, found->name);
2321                         found = home;
2322                         continue;
2323                 }
2324
2325                 /*
2326                  *      Ignore servers which are busier than the one
2327                  *      we found.
2328                  */
2329                 if (home->currently_outstanding > found->currently_outstanding) {
2330                         RDEBUG3("PROXY Skipping %s: It's busier than %s",
2331                                home->name, found->name);
2332                         continue;
2333                 }
2334
2335                 /*
2336                  *      From the list of servers which have the same
2337                  *      load, choose one at random.
2338                  */
2339                 if (((count + 1) * (fr_rand() & 0xffff)) < (uint32_t) 0x10000) {
2340                         found = home;
2341                 }
2342         } /* loop over the home servers */
2343
2344         /*
2345          *      We have no live servers, BUT we have a zombie.  Use
2346          *      the zombie as a last resort.
2347          */
2348         if (!found && zombie) {
2349                 found = zombie;
2350                 zombie = NULL;
2351         }
2352
2353         /*
2354          *      There's a fallback if they're all dead.
2355          */
2356         if (!found && pool->fallback) {
2357                 found = pool->fallback;
2358
2359                 DEBUGW("Home server pool %s failing over to fallback %s",
2360                       pool->name, found->server);
2361                 if (pool->in_fallback) goto update_and_return;
2362
2363                 pool->in_fallback = TRUE;
2364                 
2365                 /*
2366                  *      Run the trigger once an hour saying that
2367                  *      they're all dead.
2368                  */
2369                 if ((pool->time_all_dead + 3600) < request->timestamp) {
2370                         pool->time_all_dead = request->timestamp;
2371                         exec_trigger(request, pool->cs, "home_server_pool.fallback", FALSE);
2372                 }
2373         }
2374
2375         if (found) {
2376         update_and_return:
2377                 if ((found != pool->fallback) && pool->in_fallback) {
2378                         pool->in_fallback = FALSE;
2379                         exec_trigger(request, pool->cs, "home_server_pool.normal", FALSE);
2380                 }
2381
2382                 return found;
2383         }
2384
2385         /*
2386          *      No live match found, and no fallback to the "DEFAULT"
2387          *      realm.  We fix this by blindly marking all servers as
2388          *      "live".  But only do it for ones that don't support
2389          *      "pings", as they will be marked live when they
2390          *      actually are live.
2391          */
2392         if (!realm_config->fallback &&
2393             realm_config->wake_all_if_all_dead) {
2394                 for (count = 0; count < pool->num_home_servers; count++) {
2395                         home_server *home = pool->servers[count];
2396
2397                         if (!home) continue;
2398
2399                         if ((home->state == HOME_STATE_IS_DEAD) &&
2400                             (home->ping_check == HOME_PING_CHECK_NONE)) {
2401                                 home->state = HOME_STATE_ALIVE;
2402                                 if (!found) found = home;
2403                         }
2404                 }
2405
2406                 if (found) goto update_and_return;
2407         }
2408
2409         /*
2410          *      Still nothing.  Look up the DEFAULT realm, but only
2411          *      if we weren't looking up the NULL or DEFAULT realms.
2412          */
2413         if (realm_config->fallback &&
2414             realmname &&
2415             (strcmp(realmname, "NULL") != 0) &&
2416             (strcmp(realmname, "DEFAULT") != 0)) {
2417                 REALM *rd = realm_find("DEFAULT");
2418
2419                 if (!rd) return NULL;
2420
2421                 pool = NULL;
2422                 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2423                         pool = rd->auth_pool;
2424
2425                 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2426                         pool = rd->acct_pool;
2427                 }
2428                 if (!pool) return NULL;
2429
2430                 RDEBUG2("PROXY - realm %s has no live home servers.  Falling back to the DEFAULT realm.", realmname);
2431                 return home_server_ldb(rd->name, pool, request);
2432         }
2433
2434         /*
2435          *      Still haven't found anything.  Oh well.
2436          */
2437         return NULL;
2438 }
2439
2440
2441 home_server *home_server_find(fr_ipaddr_t *ipaddr, int port, int proto)
2442 {
2443         home_server myhome;
2444
2445         memset(&myhome, 0, sizeof(myhome));
2446         myhome.ipaddr = *ipaddr;
2447         myhome.src_ipaddr.af = ipaddr->af;
2448         myhome.port = port;
2449 #ifdef WITH_TCP
2450         myhome.proto = proto;
2451 #else
2452         myhome.proto = IPPROTO_UDP;
2453 #endif
2454         myhome.server = NULL;   /* we're not called for internal proxying */
2455
2456         return rbtree_finddata(home_servers_byaddr, &myhome);
2457 }
2458
2459 #ifdef WITH_COA
2460 home_server *home_server_byname(const char *name, int type)
2461 {
2462         home_server myhome;
2463
2464         memset(&myhome, 0, sizeof(myhome));
2465         myhome.type = type;
2466         myhome.name = name;
2467
2468         return rbtree_finddata(home_servers_byname, &myhome);
2469 }
2470 #endif
2471
2472 #ifdef WITH_STATS
2473 home_server *home_server_bynumber(int number)
2474 {
2475         home_server myhome;
2476
2477         memset(&myhome, 0, sizeof(myhome));
2478         myhome.number = number;
2479         myhome.server = NULL;   /* we're not called for internal proxying */
2480
2481         return rbtree_finddata(home_servers_bynumber, &myhome);
2482 }
2483 #endif
2484
2485 home_pool_t *home_pool_byname(const char *name, int type)
2486 {
2487         home_pool_t mypool;
2488         
2489         memset(&mypool, 0, sizeof(mypool));
2490         mypool.name = name;
2491         mypool.server_type = type;
2492         return rbtree_finddata(home_pools_byname, &mypool);
2493 }
2494
2495 #endif