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