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