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