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