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