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