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