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