Keep track of total requests sent to a 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 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/rad_assert.h>
29
30 #include <sys/stat.h>
31
32 #include <ctype.h>
33 #include <fcntl.h>
34
35 static rbtree_t *realms_byname = NULL;
36
37 static rbtree_t *home_servers_byaddr = NULL;
38 static rbtree_t *home_servers_byname = NULL;
39
40 static rbtree_t *home_pools_byname = NULL;
41
42 static int realm_name_cmp(const void *one, const void *two)
43 {
44         const REALM *a = one;
45         const REALM *b = two;
46
47         return strcasecmp(a->name, b->name);
48 }
49
50
51 static int home_server_name_cmp(const void *one, const void *two)
52 {
53         const home_server *a = one;
54         const home_server *b = two;
55
56         if (a->type < b->type) return -1;
57         if (a->type > b->type) return +1;
58
59         return strcasecmp(a->name, b->name);
60 }
61
62 static int home_server_addr_cmp(const void *one, const void *two)
63 {
64         const home_server *a = one;
65         const home_server *b = two;
66
67         if (a->port < b->port) return -1;
68         if (a->port > b->port) return +1;
69
70         return lrad_ipaddr_cmp(&a->ipaddr, &b->ipaddr);
71 }
72
73
74 static int home_pool_name_cmp(const void *one, const void *two)
75 {
76         const home_pool_t *a = one;
77         const home_pool_t *b = two;
78
79         if (a->server_type < b->server_type) return -1;
80         if (a->server_type > b->server_type) return +1;
81
82         return strcasecmp(a->name, b->name);
83 }
84
85
86 void realms_free(void)
87 {
88         rbtree_free(home_servers_byname);
89         home_servers_byname = NULL;
90
91         rbtree_free(home_servers_byaddr);
92         home_servers_byaddr = NULL;
93
94         rbtree_free(home_pools_byname);
95         home_pools_byname = NULL;
96
97         rbtree_free(realms_byname);
98         realms_byname = NULL;
99 }
100
101
102 int realms_init(CONF_SECTION *config)
103 {
104         CONF_SECTION *cs;
105
106         if (realms_byname) return 1;
107
108         realms_byname = rbtree_create(realm_name_cmp, free, 0);
109         if (!realms_byname) {
110                 realms_free();
111                 return 0;
112         }
113
114         home_servers_byaddr = rbtree_create(home_server_addr_cmp, free, 0);
115         if (!home_servers_byaddr) {
116                 realms_free();
117                 return 0;
118         }
119
120         home_servers_byname = rbtree_create(home_server_name_cmp, NULL, 0);
121         if (!home_servers_byname) {
122                 realms_free();
123                 return 0;
124         }
125
126         home_pools_byname = rbtree_create(home_pool_name_cmp, free, 0);
127         if (!home_pools_byname) {
128                 realms_free();
129                 return 0;
130         }
131
132         for (cs = cf_subsection_find_next(config, NULL, "realm");
133              cs != NULL;
134              cs = cf_subsection_find_next(config, cs, "realm")) {
135                 if (!realm_add(cs)) {
136                         realms_free();
137                         return 0;
138                 }
139         }
140
141         return 1;
142 }
143
144 static struct in_addr hs_ip4addr;
145 static struct in6_addr hs_ip6addr;
146 static char *hs_type = NULL;
147 static char *hs_check = NULL;
148
149 static CONF_PARSER home_server_config[] = {
150         { "ipaddr",  PW_TYPE_IPADDR,
151           0, &hs_ip4addr,  NULL },
152         { "ipv6addr",  PW_TYPE_IPV6ADDR,
153           0, &hs_ip6addr, NULL },
154
155         { "port", PW_TYPE_INTEGER,
156           offsetof(home_server,port), NULL,   "0" },
157
158         { "type",  PW_TYPE_STRING_PTR,
159           0, &hs_type, NULL },
160
161         { "secret",  PW_TYPE_STRING_PTR,
162           offsetof(home_server,secret), NULL,  NULL},
163
164         { "response_window", PW_TYPE_INTEGER,
165           offsetof(home_server,response_window), NULL,   "30" },
166         { "max_outstanding", PW_TYPE_INTEGER,
167           offsetof(home_server,max_outstanding), NULL,   "65536" },
168
169         { "zombie_period", PW_TYPE_INTEGER,
170           offsetof(home_server,zombie_period), NULL,   "40" },
171         { "status_check", PW_TYPE_STRING_PTR,
172           0, &hs_check,   "none" },
173         { "ping_check", PW_TYPE_STRING_PTR,
174           0, &hs_check,   "none" },
175
176         { "ping_interval", PW_TYPE_INTEGER,
177           offsetof(home_server,ping_interval), NULL,   "30" },
178         { "check_interval", PW_TYPE_INTEGER,
179           offsetof(home_server,ping_interval), NULL,   "30" },
180         { "num_answers_to_alive", PW_TYPE_INTEGER,
181           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
182         { "num_pings_to_alive", PW_TYPE_INTEGER,
183           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
184         { "revive_interval", PW_TYPE_INTEGER,
185           offsetof(home_server,revive_interval), NULL,   "300" },
186         { "status_check_timeout", PW_TYPE_INTEGER,
187           offsetof(home_server,ping_timeout), NULL,   "4" },
188
189         { "username",  PW_TYPE_STRING_PTR,
190           offsetof(home_server,ping_user_name), NULL,  NULL},
191         { "password",  PW_TYPE_STRING_PTR,
192           offsetof(home_server,ping_user_password), NULL,  NULL},
193
194         { NULL, -1, 0, NULL, NULL }             /* end the list */
195
196 };
197
198
199 static int home_server_add(CONF_SECTION *cs, int type)
200 {
201         const char *name2;
202         home_server *home;
203         int dual = FALSE;
204
205         name2 = cf_section_name1(cs);
206         if (!name2 || (strcasecmp(name2, "home_server") != 0)) {
207                 cf_log_err(cf_sectiontoitem(cs),
208                            "Section is not a home_server.");
209                 return 0;
210         }
211
212         name2 = cf_section_name2(cs);
213         if (!name2) {
214                 cf_log_err(cf_sectiontoitem(cs),
215                            "Home server section is missing a name.");
216                 return 0;
217         }
218
219         home = rad_malloc(sizeof(*home));
220         memset(home, 0, sizeof(*home));
221
222         home->name = name2;
223
224         memset(&hs_ip4addr, 0, sizeof(hs_ip4addr));
225         memset(&hs_ip6addr, 0, sizeof(hs_ip6addr));
226         cf_section_parse(cs, home, home_server_config);
227
228         if ((htonl(hs_ip4addr.s_addr) == INADDR_NONE) &&
229             IN6_IS_ADDR_UNSPECIFIED(&hs_ip6addr)) {
230                 cf_log_err(cf_sectiontoitem(cs),
231                            "No IPv4 or IPv6 address defined for home server %s.",
232                            name2);
233                 free(home);
234                 free(hs_type);
235                 hs_type = NULL;
236                 free(hs_check);
237                 hs_check = NULL;
238                 return 0;
239         }
240
241         /*
242          *      Figure out which one to use.
243          *
244          *      FIXME: Set hostname to something?
245          */
246         if (htonl(hs_ip4addr.s_addr) != INADDR_NONE) {
247                 home->ipaddr.af = AF_INET;
248                 home->ipaddr.ipaddr.ip4addr = hs_ip4addr;
249
250         } else if (!IN6_IS_ADDR_UNSPECIFIED(&hs_ip6addr)) {
251                 home->ipaddr.af = AF_INET6;
252                 home->ipaddr.ipaddr.ip6addr = hs_ip6addr;
253
254         } else {
255                 cf_log_err(cf_sectiontoitem(cs),
256                            "Internal sanity check failed for home server %s.",
257                            name2);
258                 free(home);
259                 free(hs_type);
260                 hs_type = NULL;
261                 free(hs_check);
262                 hs_check = NULL;
263                 return 0;
264         }
265
266         if (!home->port || (home->port > 65535)) {
267                 cf_log_err(cf_sectiontoitem(cs),
268                            "No port, or invalid port defined for home server %s.",
269                            name2);
270                 free(home);
271                 free(hs_type);
272                 hs_type = NULL;
273                 free(hs_check);
274                 hs_check = NULL;
275                 return 0;
276         }
277
278         if (0) {
279                 cf_log_err(cf_sectiontoitem(cs),
280                            "Fatal error!  Home server %s is ourselves!",
281                            name2);
282                 free(home);
283                 free(hs_type);
284                 hs_type = NULL;
285                 free(hs_check);
286                 hs_check = NULL;
287                 return 0;
288         }
289
290         if (!hs_type) {
291                 cf_log_err(cf_sectiontoitem(cs),
292                            "Fatal error!  Home server %s has no type defined!",
293                            name2);
294                 free(home);
295                 free(hs_type);
296                 hs_type = NULL;
297                 free(hs_check);
298                 hs_check = NULL;
299                 return 0;
300         }
301
302         if (strcasecmp(hs_type, "auth") == 0) {
303                 home->type = HOME_TYPE_AUTH;
304                 if (type != home->type) {
305                         cf_log_err(cf_sectiontoitem(cs),
306                                    "Server pool of \"acct\" servers cannot include home server %s of type \"auth\"",
307                                    name2);
308                         free(home);
309                         return 0;
310                 }
311
312         } else if (strcasecmp(hs_type, "acct") == 0) {
313                 home->type = HOME_TYPE_ACCT;
314                 if (type != home->type) {
315                         cf_log_err(cf_sectiontoitem(cs),
316                                    "Server pool of \"auth\" servers cannot include home server %s of type \"acct\"",
317                                    name2);
318                         free(home);
319                         return 0;
320                 }
321
322         } else if (strcasecmp(hs_type, "auth+acct") == 0) {
323                 home->type = HOME_TYPE_AUTH;
324                 dual = TRUE;
325
326         } else {
327                 cf_log_err(cf_sectiontoitem(cs),
328                            "Invalid type \"%s\" for home server %s.",
329                            hs_type, name2);
330                 free(home);
331                 free(hs_type);
332                 hs_type = NULL;
333                 free(hs_check);
334                 hs_check = NULL;
335                 return 0;
336         }
337         free(hs_type);
338         hs_type = NULL;
339
340         if (!home->secret) {
341                 cf_log_err(cf_sectiontoitem(cs),
342                            "No shared secret defined for home server %s.",
343                            name2);
344                 free(home);
345                 return 0;
346         }
347
348         if (!hs_check || (strcasecmp(hs_check, "none") == 0)) {
349                 home->ping_check = HOME_PING_CHECK_NONE;
350
351         } else if (strcasecmp(hs_check, "status-server") == 0) {
352                 home->ping_check = HOME_PING_CHECK_STATUS_SERVER;
353
354         } else if (strcasecmp(hs_check, "request") == 0) {
355                 home->ping_check = HOME_PING_CHECK_REQUEST;
356
357         } else {
358                 cf_log_err(cf_sectiontoitem(cs),
359                            "Invalid ping_check \"%s\" for home server %s.",
360                            hs_check, name2);
361                 free(home);
362                 free(hs_check);
363                 hs_check = NULL;
364                 return 0;
365         }
366         free(hs_check);
367         hs_check = NULL;
368
369         if ((home->ping_check != HOME_PING_CHECK_NONE) &&
370             (home->ping_check != HOME_PING_CHECK_STATUS_SERVER)) {
371                 if (!home->ping_user_name) {
372                         cf_log_err(cf_sectiontoitem(cs), "You must supply a user name to enable ping checks");
373                         free(home);
374                         return 0;
375                 }
376
377                 if ((home->type == HOME_TYPE_AUTH) &&
378                     !home->ping_user_password) {
379                         cf_log_err(cf_sectiontoitem(cs), "You must supply a password to enable ping checks");
380                         free(home);
381                         return 0;
382                 }
383         }
384
385         if (rbtree_finddata(home_servers_byaddr, home)) {
386                 DEBUG2("Ignoring duplicate home server %s.", name2);
387                 return 1;
388         }
389
390         if (!rbtree_insert(home_servers_byname, home)) {
391                 cf_log_err(cf_sectiontoitem(cs),
392                            "Internal error adding home server %s.",
393                            name2);
394                 free(home);
395                 return 0;
396         }
397
398         if (!rbtree_insert(home_servers_byaddr, home)) {
399                 rbtree_deletebydata(home_servers_byname, home);
400                 cf_log_err(cf_sectiontoitem(cs),
401                            "Internal error adding home server %s.",
402                            name2);
403                 free(home);
404                 return 0;
405         }
406
407         if (home->response_window < 5) home->response_window = 5;
408         if (home->response_window > 60) home->response_window = 60;
409
410         if (home->max_outstanding < 8) home->max_outstanding = 8;
411         if (home->max_outstanding > 65536*16) home->max_outstanding = 65536*16;
412
413         if (home->ping_interval < 6) home->ping_interval = 6;
414         if (home->ping_interval > 120) home->ping_interval = 120;
415
416         if (home->zombie_period < 20) home->zombie_period = 20;
417         if (home->zombie_period > 120) home->zombie_period = 120;
418
419         if (home->zombie_period < home->response_window) {
420                 home->zombie_period = home->response_window;
421         }
422
423         if (home->num_pings_to_alive < 3) home->num_pings_to_alive = 3;
424         if (home->num_pings_to_alive > 10) home->num_pings_to_alive = 10;
425
426         if (home->ping_timeout < 3) home->ping_timeout = 3;
427         if (home->ping_timeout > 10) home->ping_timeout = 10;
428
429         if (home->revive_interval < 60) home->revive_interval = 60;
430         if (home->revive_interval > 3600) home->revive_interval = 3600;
431
432         if (dual) {
433                 home_server *home2 = rad_malloc(sizeof(*home2));
434
435                 memcpy(home2, home, sizeof(*home2));
436
437                 home2->type = HOME_TYPE_ACCT;
438                 home2->port++;
439                 home2->ping_user_password = NULL;
440
441                 if (!rbtree_insert(home_servers_byname, home2)) {
442                         cf_log_err(cf_sectiontoitem(cs),
443                                    "Internal error adding home server %s.",
444                                    name2);
445                         free(home2);
446                         return 0;
447                 }
448                 
449                 if (!rbtree_insert(home_servers_byaddr, home2)) {
450                         rbtree_deletebydata(home_servers_byname, home2);
451                         cf_log_err(cf_sectiontoitem(cs),
452                                    "Internal error adding home server %s.",
453                                    name2);
454                         free(home2);
455                         return 0;
456                 }
457         }
458
459         return 1;
460 }
461
462
463 static int server_pool_add(CONF_SECTION *cs, int server_type, int do_print)
464 {
465         const char *name2;
466         home_pool_t *pool = NULL;
467         const char *value;
468         CONF_PAIR *cp;
469         int num_home_servers;
470
471         name2 = cf_section_name1(cs);
472         if (!name2 || (strcasecmp(name2, "server_pool") != 0)) {
473                 cf_log_err(cf_sectiontoitem(cs),
474                            "Section is not a server_pool.");
475                 return 0;
476         }
477
478         name2 = cf_section_name2(cs);
479         if (!name2) {
480                 cf_log_err(cf_sectiontoitem(cs),
481                            "Server pool section is missing a name.");
482                 return 0;
483         }
484
485         /*
486          *      Count the home servers and initalize them.
487          */
488         num_home_servers = 0;
489         for (cp = cf_pair_find(cs, "home_server");
490              cp != NULL;
491              cp = cf_pair_find_next(cs, cp, "home_server")) {
492                 home_server myhome, *home;
493                 CONF_SECTION *server_cs;
494
495                 num_home_servers++;
496
497                 value = cf_pair_value(cp);
498                 if (!value) {
499                         cf_log_err(cf_pairtoitem(cp),
500                                    "No value given for home_server.");
501                         return 0;;
502                 }
503
504                 myhome.name = value;
505                 myhome.type = server_type;
506                 home = rbtree_finddata(home_servers_byname, &myhome);
507                 if (home) continue;
508
509                 server_cs = cf_section_sub_find_name2(mainconfig.config,
510                                                       "home_server",
511                                                       value);
512                 if (!server_cs) {
513                         cf_log_err(cf_pairtoitem(cp),
514                                    "Unknown home_server \"%s\".",
515                                    value);
516                         return 0;
517                 }
518
519                 if (!home_server_add(server_cs, server_type)) {
520                         return 0;
521                 }
522
523                 home = rbtree_finddata(home_servers_byname, &myhome);
524                 if (!home) {
525                         radlog(L_ERR, "Internal sanity check failed %d",
526                                __LINE__);
527                         return 0;
528                 }
529         }
530
531         if (num_home_servers == 0) {
532                 cf_log_err(cf_sectiontoitem(cs),
533                            "No home servers defined in pool %s",
534                            name2);
535                 goto error;
536         }
537
538         pool = rad_malloc(sizeof(*pool) + num_home_servers * sizeof(pool->servers[0]));
539         memset(pool, 0, sizeof(*pool) + num_home_servers * sizeof(pool->servers[0]));
540
541         pool->type = HOME_POOL_FAIL_OVER;
542         pool->name = name2;
543         pool->server_type = server_type;
544
545         if (do_print) DEBUG2(" server_pool %s {", name2);
546
547         cp = cf_pair_find(cs, "type");
548         if (cp) {
549                 static LRAD_NAME_NUMBER pool_types[] = {
550                         { "load-balance", HOME_POOL_LOAD_BALANCE },
551                         { "fail-over", HOME_POOL_FAIL_OVER },
552                         { "round_robin", HOME_POOL_LOAD_BALANCE },
553                         { "fail_over", HOME_POOL_FAIL_OVER },
554                         { "client-balance", HOME_POOL_CLIENT_BALANCE },
555                         { "client-port-balance", HOME_POOL_CLIENT_PORT_BALANCE },
556                         { "keyed-balance", HOME_POOL_KEYED_BALANCE },
557                         { NULL, 0 }
558                 };
559
560                 value = cf_pair_value(cp);
561                 if (!value) {
562                         cf_log_err(cf_pairtoitem(cp),
563                                    "No value given for type.");
564                         goto error;
565                 }
566
567                 pool->type = lrad_str2int(pool_types, value, 0);
568                 if (!pool->type) {
569                         cf_log_err(cf_pairtoitem(cp),
570                                    "Unknown type \"%s\".",
571                                    value);
572                         goto error;
573                 }
574
575                 if (do_print) DEBUG2("\ttype = %s", value);
576         }
577
578         for (cp = cf_pair_find(cs, "home_server");
579              cp != NULL;
580              cp = cf_pair_find_next(cs, cp, "home_server")) {
581                 home_server myhome, *home;
582
583                 value = cf_pair_value(cp);
584                 if (!value) {
585                         cf_log_err(cf_pairtoitem(cp),
586                                    "No value given for home_server.");
587                         goto error;
588                 }
589
590                 myhome.name = value;
591                 myhome.type = server_type;
592
593                 home = rbtree_finddata(home_servers_byname, &myhome);
594                 if (!home) {
595                         DEBUG2("Internal sanity check failed");
596                         goto error;
597                 }
598
599                 if (0) {
600                         DEBUG2("Warning: Duplicate home server %s in server pool %s", home->name, pool->name);
601                         continue;
602                 }
603
604                 if (do_print) DEBUG2("\thome_server = %s", home->name);
605                 pool->servers[pool->num_home_servers] = home;
606                 pool->num_home_servers++;
607         } /* loop over home_server's */
608
609         if (!rbtree_insert(home_pools_byname, pool)) {
610                 rad_assert("Internal sanity check failed");
611                 goto error;
612         }
613
614         if (do_print) DEBUG2(" }");
615
616         rad_assert(pool->server_type != 0);
617
618         return 1;
619
620  error:
621         if (do_print) DEBUG2(" }");
622         free(pool);
623         return 0;
624 }
625
626
627 static int old_server_add(CONF_SECTION *cs, const char *realm,
628                           const char *name, const char *secret,
629                           home_pool_type_t ldflag, home_pool_t **pool_p,
630                           int type)
631 {
632         int i, insert_point, num_home_servers;
633         home_server myhome, *home;
634         home_pool_t mypool, *pool;
635         CONF_SECTION *subcs;
636
637         /*
638          *      LOCAL realms get sanity checked, and nothing else happens.
639          */
640         if (strcmp(name, "LOCAL") == 0) {
641                 if (*pool_p) {
642                         cf_log_err(cf_sectiontoitem(cs), "Realm \"%s\" cannot be both LOCAL and remote", name);
643                         return 0;
644                 }
645                 return 1;
646         }
647
648         mypool.name = realm;
649         mypool.server_type = type;
650         pool = rbtree_finddata(home_pools_byname, &mypool);
651         if (pool) {
652                 if (pool->type != ldflag) {
653                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent ldflag for server pool \"%s\"", name);
654                         return 0;
655                 }
656
657                 if (pool->server_type != type) {
658                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent home server type for server pool \"%s\"", name);
659                         return 0;
660                 }
661         }
662
663         myhome.name = name;
664         myhome.type = type;
665         home = rbtree_finddata(home_servers_byname, &myhome);
666         if (home) {
667                 if (strcmp(home->secret, secret) != 0) {
668                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent shared secret for home server \"%s\"", name);
669                         return 0;
670                 }
671
672                 if (home->type != type) {
673                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent type for home server \"%s\"", name);
674                         return 0;
675                 }
676
677                 /*
678                  *      See if the home server is already listed
679                  *      in the pool.  If so, do nothing else.
680                  */
681                 if (pool) for (i = 0; i < pool->num_home_servers; i++) {
682                         if (pool->servers[i] == home) {
683                                 return 1;
684                         }
685                 }
686         }
687
688         /*
689          *      If we do have a pool, check that there is room to
690          *      insert the home server we've found, or the one that we
691          *      create here.
692          *
693          *      Note that we insert it into the LAST available
694          *      position, in order to maintain the same order as in
695          *      the configuration files.
696          */
697         insert_point = -1;
698         if (pool) {
699                 for (i = pool->num_home_servers - 1; i >= 0; i--) {
700                         if (pool->servers[i]) break;
701
702                         if (!pool->servers[i]) {
703                                 insert_point = i;
704                         }
705                 }
706
707                 if (insert_point < 0) {
708                         cf_log_err(cf_sectiontoitem(cs), "No room in pool to add home server \"%s\".  Please update the realm configuration to use the new-style home servers and server pools.", name);
709                         return 0;
710                 }
711         }
712
713         /*
714          *      No home server, allocate one.
715          */
716         if (!home) {
717                 const char *p;
718                 char *q;
719
720                 home = rad_malloc(sizeof(*home));
721                 memset(home, 0, sizeof(*home));
722
723                 home->name = name;
724                 home->hostname = name;
725                 home->type = type;
726                 home->secret = secret;
727
728                 p = strchr(name, ':');
729                 if (!p) {
730                         if (type == HOME_TYPE_AUTH) {
731                                 home->port = PW_AUTH_UDP_PORT;
732                         } else {
733                                 home->port = PW_ACCT_UDP_PORT;
734                         }
735
736                         p = name;
737                         q = NULL;
738
739                 } else if (p == name) {
740                                 cf_log_err(cf_sectiontoitem(cs),
741                                            "Invalid hostname %s.",
742                                            name);
743                                 free(home);
744                                 return 0;
745
746                 } else {
747                         home->port = atoi(p + 1);
748                         if ((home->port == 0) || (home->port > 65535)) {
749                                 cf_log_err(cf_sectiontoitem(cs),
750                                            "Invalid port %s.",
751                                            p + 1);
752                                 free(home);
753                                 return 0;
754                         }
755
756                         q = rad_malloc((p - name) + 1);
757                         memcpy(q, name, (p - name));
758                         q[p - name] = '\0';
759                         p = q;
760                 }
761
762                 if (ip_hton(p, AF_UNSPEC, &home->ipaddr) < 0) {
763                         cf_log_err(cf_sectiontoitem(cs),
764                                    "Failed looking up hostname %s.",
765                                    p);
766                         free(home);
767                         free(q);
768                         return 0;
769                 }
770                 free(q);
771
772                 /*
773                  *      Use the old-style configuration.
774                  */
775                 home->max_outstanding = 65535*16;
776                 home->zombie_period = mainconfig.proxy_retry_delay * mainconfig.proxy_retry_count;
777                 if (home->zombie_period == 0) home->zombie_period =30;
778                 home->response_window = home->zombie_period - 1;
779
780                 home->ping_check = HOME_PING_CHECK_NONE;
781
782                 home->revive_interval = mainconfig.proxy_dead_time;
783
784                 if (rbtree_finddata(home_servers_byaddr, home)) {
785                         cf_log_err(cf_sectiontoitem(cs), "Home server %s has the same IP address and/or port as another home server.", name);
786                         free(home);
787                         return 0;
788                 }
789
790                 if (!rbtree_insert(home_servers_byname, home)) {
791                         cf_log_err(cf_sectiontoitem(cs), "Internal error adding home server %s.", name);
792                         free(home);
793                         return 0;
794                 }
795
796                 if (!rbtree_insert(home_servers_byaddr, home)) {
797                         rbtree_deletebydata(home_servers_byname, home);
798                         cf_log_err(cf_sectiontoitem(cs), "Internal error adding home server %s.", name);
799                         free(home);
800                         return 0;
801                 }
802         }
803
804         /*
805          *      We now have a home server, see if we can insert it
806          *      into pre-existing pool.
807          */
808         if (insert_point >= 0) {
809                 rad_assert(pool != NULL);
810                 pool->servers[insert_point] = home;
811                 return 1;
812         }
813
814         rad_assert(pool == NULL);
815         rad_assert(home != NULL);
816
817         /*
818          *      Count the old-style realms of this name.
819          */
820         num_home_servers = 0;
821         for (subcs = cf_section_find_next(cs, NULL, "realm");
822              subcs != NULL;
823              subcs = cf_section_find_next(cs, subcs, "realm")) {
824                 const char *this = cf_section_name2(subcs);
825
826                 if (!this || (strcmp(this, realm) != 0)) continue;
827                 num_home_servers++;
828         }
829
830         if (num_home_servers == 0) {
831                 cf_log_err(cf_sectiontoitem(cs), "Internal error counting pools for home server %s.", name);
832                 free(home);
833                 return 0;
834         }
835
836         pool = rad_malloc(sizeof(*pool) + num_home_servers * sizeof(pool->servers[0]));
837         memset(pool, 0, sizeof(*pool) + num_home_servers * sizeof(pool->servers[0]));
838
839         pool->name = realm;
840         pool->type = ldflag;
841         pool->server_type = type;
842         pool->num_home_servers = num_home_servers;
843         pool->servers[0] = home;
844
845         if (!rbtree_insert(home_pools_byname, pool)) {
846                 rad_assert("Internal sanity check failed");
847                 return 0;
848         }
849
850         *pool_p = pool;
851
852         return 1;
853 }
854
855 static int old_realm_config(CONF_SECTION *cs, REALM *r)
856 {
857         char *host;
858         const char *secret = NULL;
859         home_pool_type_t ldflag;
860         CONF_PAIR *cp;
861
862         cp = cf_pair_find(cs, "ldflag");
863         ldflag = HOME_POOL_FAIL_OVER;
864         if (cp) {
865                 host = cf_pair_value(cp);
866                 if (!host) {
867                         cf_log_err(cf_pairtoitem(cp), "No value specified for ldflag");
868                         return 0;
869                 }
870
871                 if (strcasecmp(host, "fail_over") == 0) {
872                         DEBUG2("\tldflag = fail_over");
873                         
874                 } else if (strcasecmp(host, "round_robin") == 0) {
875                         ldflag = HOME_POOL_LOAD_BALANCE;
876                         DEBUG2("\tldflag = round_robin");
877                         
878                 } else {
879                         cf_log_err(cf_sectiontoitem(cs), "Unknown value \"%s\" for ldflag", host);
880                         return 0;
881                 }
882         } /* else don't print it. */
883
884         /*
885          *      Allow old-style if it doesn't exist, or if it exists and
886          *      it's LOCAL.
887          */
888         cp = cf_pair_find(cs, "authhost");
889         if (cp) {
890                 host = cf_pair_value(cp);
891                 if (!host) {
892                         cf_log_err(cf_pairtoitem(cp), "No value specified for authhost");
893                         return 0;
894                 }
895
896                 if (strcmp(host, "LOCAL") != 0) {
897                         cp = cf_pair_find(cs, "secret");
898                         if (!cp) {
899                                 cf_log_err(cf_sectiontoitem(cs), "No shared secret supplied for realm: %s", r->name);
900                                 return 0;
901                         }
902
903                         secret = cf_pair_value(cp);
904                         if (!secret) {
905                                 cf_log_err(cf_pairtoitem(cp), "No value specified for secret");
906                                 return 0;
907                         }
908                 }
909                         
910                 DEBUG2("\tauthhost = %s",  host);
911
912                 if (!old_server_add(cs, r->name, host, secret, ldflag,
913                                     &r->auth_pool, HOME_TYPE_AUTH)) {
914                         return 0;
915                 }
916         }
917
918         cp = cf_pair_find(cs, "accthost");
919         if (cp) {
920                 host = cf_pair_value(cp);
921                 if (!host) {
922                         cf_log_err(cf_pairtoitem(cp), "No value specified for accthost");
923                         return 0;
924                 }
925
926                 /*
927                  *      Don't look for a secret again if it was found
928                  *      above.
929                  */
930                 if ((strcmp(host, "LOCAL") != 0) && !secret) {
931                         cp = cf_pair_find(cs, "secret");
932                         if (!cp) {
933                                 cf_log_err(cf_sectiontoitem(cs), "No shared secret supplied for realm: %s", r->name);
934                                 return 0;
935                         }
936                         
937                         secret = cf_pair_value(cp);
938                         if (!secret) {
939                                 cf_log_err(cf_pairtoitem(cp), "No value specified for secret");
940                                 return 0;
941                         }
942                 }
943                 
944                 DEBUG2("\taccthost = %s", host);
945
946                 if (!old_server_add(cs, r->name, host, secret, ldflag,
947                                     &r->acct_pool, HOME_TYPE_ACCT)) {
948                         return 0;
949                 }
950         }
951
952         if (secret) DEBUG2("\tsecret = %s", secret);
953
954         return 1;
955
956 }
957
958
959 static int add_pool_to_realm(CONF_SECTION *cs,
960                              const char *name, home_pool_t **dest,
961                              int server_type, int do_print)
962 {
963         home_pool_t mypool, *pool;
964
965         mypool.name = name;
966         mypool.server_type = server_type;
967
968         pool = rbtree_finddata(home_pools_byname, &mypool);
969         if (!pool) {
970                 CONF_SECTION *pool_cs;
971
972                 pool_cs = cf_section_sub_find_name2(mainconfig.config,
973                                                     "server_pool",
974                                                     name);
975                 if (!pool_cs) {
976                         cf_log_err(cf_sectiontoitem(cs), "Failed to find server_pool \"%s\"", name);
977                         return 0;
978                 }
979
980                 if (!server_pool_add(pool_cs, server_type, do_print)) {
981                         return 0;
982                 }
983
984                 pool = rbtree_finddata(home_pools_byname, &mypool);
985                 if (!pool) {
986                         radlog(L_ERR, "Internal sanity check failed in add_pool_to_realm");
987                         return 0;
988                 }
989         }
990
991         if (pool->server_type != server_type) {
992                 cf_log_err(cf_sectiontoitem(cs), "Incompatible server_pool \"%s\" (mixed auth_pool / acct_pool)", name);
993                 return 0;
994         }
995
996         *dest = pool;
997
998         return 1;
999 }
1000
1001 int realm_add(CONF_SECTION *cs)
1002 {
1003         const char *name2;
1004         REALM *r = NULL;
1005         CONF_PAIR *cp;
1006         home_pool_t *auth_pool, *acct_pool;
1007         const char *auth_pool_name, *acct_pool_name;
1008
1009         name2 = cf_section_name1(cs);
1010         if (!name2 || (strcasecmp(name2, "realm") != 0)) {
1011                 cf_log_err(cf_sectiontoitem(cs), "Section is not a realm.");
1012                 return 0;
1013         }
1014
1015         name2 = cf_section_name2(cs);
1016         if (!name2) {
1017                 cf_log_err(cf_sectiontoitem(cs), "Realm section is missing the realm name.");
1018                 return 0;
1019         }
1020
1021         auth_pool = acct_pool = NULL;
1022         auth_pool_name = acct_pool_name = NULL;
1023
1024         /*
1025          *      Prefer new configuration to old one.
1026          */
1027         cp = cf_pair_find(cs, "pool");
1028         if (cp) auth_pool_name = cf_pair_value(cp);
1029         if (cp && auth_pool_name) {
1030                 acct_pool_name = auth_pool_name;
1031                 if (!add_pool_to_realm(cs,
1032                                        auth_pool_name, &auth_pool,
1033                                        HOME_TYPE_AUTH, 1)) {
1034                         return 0;
1035                 }
1036                 if (!add_pool_to_realm(cs,
1037                                        auth_pool_name, &acct_pool,
1038                                        HOME_TYPE_ACCT, 0)) {
1039                         return 0;
1040                 }
1041         }
1042
1043         cp = cf_pair_find(cs, "auth_pool");
1044         if (cp) auth_pool_name = cf_pair_value(cp);
1045         if (cp && auth_pool_name) {
1046                 if (auth_pool) {
1047                         cf_log_err(cf_sectiontoitem(cs), "Cannot use \"pool\" and \"auth_pool\" at the same time.");
1048                         return 0;
1049                 }
1050                 if (!add_pool_to_realm(cs,
1051                                        auth_pool_name, &auth_pool,
1052                                        HOME_TYPE_AUTH, 1)) {
1053                         return 0;
1054                 }
1055         }
1056
1057         cp = cf_pair_find(cs, "acct_pool");
1058         if (cp) acct_pool_name = cf_pair_value(cp);
1059         if (cp && acct_pool_name) {
1060                 int do_print = TRUE;
1061
1062                 if (acct_pool) {
1063                         cf_log_err(cf_sectiontoitem(cs), "Cannot use \"pool\" and \"acct_pool\" at the same time.");
1064                         return 0;
1065                 }
1066
1067                 if (!auth_pool ||
1068                     (strcmp(auth_pool_name, acct_pool_name) != 0)) {
1069                         do_print = TRUE;
1070                 }
1071
1072                 if (!add_pool_to_realm(cs,
1073                                        acct_pool_name, &acct_pool,
1074                                        HOME_TYPE_ACCT, do_print)) {
1075                         return 0;
1076                 }
1077         }
1078
1079         DEBUG2(" realm %s {", name2);
1080
1081         /*
1082          *      The realm MAY already exist if it's an old-style realm.
1083          *      In that case, merge the old-style realm with this one.
1084          */
1085         r = realm_find(name2);
1086         if (r) {
1087                 if (cf_pair_find(cs, "auth_pool") ||
1088                     cf_pair_find(cs, "acct_pool")) {
1089                         cf_log_err(cf_sectiontoitem(cs), "Duplicate realm \"%s\"", name2);
1090                         goto error;
1091                 }
1092
1093                 if (!old_realm_config(cs, r)) {
1094                         goto error;
1095                 }
1096
1097                 DEBUG2(" } # realm %s", name2);
1098                 return 1;
1099         }
1100
1101         r = rad_malloc(sizeof(*r));
1102         memset(r, 0, sizeof(*r));
1103
1104         r->name = name2;
1105         r->auth_pool = auth_pool;
1106         r->acct_pool = acct_pool;
1107         r->striprealm = 1;
1108
1109         if (auth_pool_name &&
1110             (auth_pool_name == acct_pool_name)) { /* yes, ptr comparison */
1111                 DEBUG2("\tpool = %s", auth_pool_name);
1112         } else {
1113                 if (auth_pool_name) DEBUG2("\tauth_pool = %s", auth_pool_name);
1114                 if (acct_pool_name) DEBUG2("\tacct_pool = %s", acct_pool_name);
1115         }
1116
1117         cp = cf_pair_find(cs, "nostrip");
1118         if (cp && (cf_pair_value(cp) == NULL)) {
1119                 r->striprealm = 0;
1120                 DEBUG2("\tnostrip");
1121         }
1122
1123         /*
1124          *      We're a new-style realm.  Complain if we see the old
1125          *      directives.
1126          */
1127         if (r->auth_pool || r->acct_pool) {
1128                 if (((cp = cf_pair_find(cs, "authhost")) != NULL) ||
1129                     ((cp = cf_pair_find(cs, "accthost")) != NULL) ||
1130                     ((cp = cf_pair_find(cs, "secret")) != NULL) ||
1131                     ((cp = cf_pair_find(cs, "ldflag")) != NULL)) {
1132                         DEBUG2("WARNING: Ignoring old-style configuration entry \"%s\" in realm \"%s\"", cf_pair_attr(cp), r->name);
1133                 }
1134
1135
1136                 /*
1137                  *      The realm MAY be an old-style realm, as there
1138                  *      was no auth_pool or acct_pool.  Double-check
1139                  *      it, just to be safe.
1140                  */
1141         } else if (!old_realm_config(cs, r)) {
1142                 goto error;
1143         }
1144
1145         if (!rbtree_insert(realms_byname, r)) {
1146                 rad_assert("Internal sanity check failed");
1147                 goto error;
1148         }
1149
1150         DEBUG2(" }");
1151
1152         return 1;
1153
1154  error:
1155         DEBUG2(" } # realm %s", name2);
1156         free(r);
1157         return 0;
1158 }
1159
1160
1161 /*
1162  *      Find a realm in the REALM list.
1163  */
1164 REALM *realm_find(const char *name)
1165 {
1166         REALM myrealm;
1167
1168         if (!name) name = "NULL";
1169
1170         myrealm.name = name;
1171         return rbtree_finddata(realms_byname, &myrealm);
1172 }
1173
1174
1175 home_server *home_server_ldb(const char *realmname,
1176                              home_pool_t *pool, REQUEST *request)
1177 {
1178         int             start;
1179         int             count;
1180         home_server     *found = NULL;
1181         VALUE_PAIR      *vp;
1182
1183         start = 0;
1184
1185         /*
1186          *      Determine how to pick choose the home server.
1187          */
1188         switch (pool->type) {
1189                 uint32_t hash;
1190
1191                 /*
1192                  *      For load-balancing by client IP address, we
1193                  *      pick a home server by hashing the client IP.
1194                  *
1195                  *      This isn't as even a load distribution as
1196                  *      tracking the State attribute, but it's better
1197                  *      than nothing.
1198                  */
1199         case HOME_POOL_CLIENT_BALANCE:
1200                 switch (request->packet->src_ipaddr.af) {
1201                 case AF_INET:
1202                         hash = lrad_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
1203                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
1204                         break;
1205                 case AF_INET6:
1206                         hash = lrad_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
1207                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
1208                         break;
1209                 default:
1210                         hash = 0;
1211                         break;
1212                 }
1213                 start = hash % pool->num_home_servers;
1214                 break;
1215
1216         case HOME_POOL_CLIENT_PORT_BALANCE:
1217                 switch (request->packet->src_ipaddr.af) {
1218                 case AF_INET:
1219                         hash = lrad_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
1220                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
1221                         break;
1222                 case AF_INET6:
1223                         hash = lrad_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
1224                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
1225                         break;
1226                 default:
1227                         hash = 0;
1228                         break;
1229                 }
1230                 lrad_hash_update(&request->packet->src_port,
1231                                  sizeof(request->packet->src_port), hash);
1232                 start = hash % pool->num_home_servers;
1233                 break;
1234
1235         case HOME_POOL_KEYED_BALANCE:
1236                 if ((vp = pairfind(request->config_items, PW_LOAD_BALANCE_KEY)) != NULL) {
1237                         hash = lrad_hash(vp->vp_strvalue, vp->length);
1238                         start = hash % pool->num_home_servers;
1239                         break;
1240                 }
1241                 /* FALL-THROUGH */
1242                                 
1243         case HOME_POOL_LOAD_BALANCE:
1244                 found = pool->servers[0];
1245
1246         default:
1247                 start = 0;
1248                 break;
1249         }
1250
1251         /*
1252          *      Starting with the home server we chose, loop through
1253          *      all home servers.  If the current one is dead, skip
1254          *      it.  If it is too busy, skip it.
1255          *
1256          *      Otherwise, use it.
1257          */
1258         for (count = 0; count < pool->num_home_servers; count++) {
1259                 home_server *home = pool->servers[(start + count) % pool->num_home_servers];
1260
1261                 if (home->state == HOME_STATE_IS_DEAD) {
1262                         continue;
1263                 }
1264
1265                 /*
1266                  *      This home server is too busy.  Choose another one.
1267                  */
1268                 if (home->currently_outstanding >= home->max_outstanding) {
1269                         continue;
1270                 }
1271
1272                 if (pool->type != HOME_POOL_LOAD_BALANCE) {
1273                         return home;
1274                 }
1275
1276                 DEBUG3("PROXY %s %d\t%s %d",
1277                        found->name, found->currently_outstanding,
1278                        home->name, home->currently_outstanding);
1279
1280                 /*
1281                  *      Prefer this server if it's less busy than the
1282                  *      one we previously found.
1283                  */
1284                 if (home->currently_outstanding < found->currently_outstanding) {
1285                         DEBUG3("Choosing %s: It's less busy than %s",
1286                                home->name, found->name);
1287                         found = home;
1288                         continue;
1289                 }
1290
1291                 /*
1292                  *      Ignore servers which are busier than the one
1293                  *      we found.
1294                  */
1295                 if (home->currently_outstanding > found->currently_outstanding) {
1296                         DEBUG3("Skipping %s: It's busier than %s",
1297                                home->name, found->name);
1298                         continue;
1299                 }
1300
1301                 if (home->total_requests_sent < found->total_requests_sent) {
1302                         DEBUG3("Choosing %s: It's been less busy than %s",
1303                                home->name, found->name);
1304                         found = home;
1305                         continue;
1306                 }
1307
1308                 if (home->total_requests_sent > found->total_requests_sent) {
1309                         DEBUG3("Skipping %s: It's been busier than %s",
1310                                home->name, found->name);
1311                         continue;
1312                 }
1313
1314                 /*
1315                  *      From the list of servers which have the same
1316                  *      load, choose one at random.
1317                  */
1318                 if (((count + 1) * (lrad_rand() & 0xffff)) < (uint32_t) 0x10000) {
1319                         found = home;
1320                 }
1321
1322         } /* loop over the home servers */
1323
1324         if (found) return found;
1325
1326         /*
1327          *      No live match found, and no fallback to the "DEFAULT"
1328          *      realm.  We fix this by blindly marking all servers as
1329          *      "live".  But only do it for ones that don't support
1330          *      "pings", as they will be marked live when they
1331          *      actually are live.
1332          */
1333         if (!mainconfig.proxy_fallback &&
1334             mainconfig.wake_all_if_all_dead) {
1335                 home_server *lb = NULL;
1336
1337                 for (count = 0; count < pool->num_home_servers; count++) {
1338                         home_server *home = pool->servers[count];
1339
1340                         if ((home->state == HOME_STATE_IS_DEAD) &&
1341                             (home->ping_check == HOME_PING_CHECK_NONE)) {
1342                                 home->state = HOME_STATE_ALIVE;
1343                                 if (!lb) lb = home;
1344                         }
1345                 }
1346
1347                 if (lb) return lb;
1348         }
1349
1350         /*
1351          *      Still nothing.  Look up the DEFAULT realm, but only
1352          *      if we weren't looking up the NULL or DEFAULT realms.
1353          */
1354         if (mainconfig.proxy_fallback &&
1355             realmname &&
1356             (strcmp(realmname, "NULL") != 0) &&
1357             (strcmp(realmname, "DEFAULT") != 0)) {
1358                 REALM *rd = realm_find("DEFAULT");
1359
1360                 if (!rd) return NULL;
1361
1362                 pool = NULL;
1363                 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1364                         pool = rd->auth_pool;
1365
1366                 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1367                         pool = rd->acct_pool;
1368                 }
1369                 if (!pool) return NULL;
1370
1371                 DEBUG2("  Realm %s has no live home servers.  Falling back to the DEFAULT realm.", realmname);
1372                 return home_server_ldb(rd->name, pool, request);
1373         }
1374
1375         /*
1376          *      Still haven't found anything.  Oh well.
1377          */
1378         return NULL;
1379 }
1380
1381
1382 home_server *home_server_find(lrad_ipaddr_t *ipaddr, int port)
1383 {
1384         home_server myhome;
1385
1386         myhome.ipaddr = *ipaddr;
1387         myhome.port = port;
1388
1389         return rbtree_finddata(home_servers_byaddr, &myhome);
1390 }