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