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