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