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