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