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