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