Added "del client <ipaddr>" command for dynamic clients
[freeradius.git] / src / main / client.c
1 /*
2  * client.c     Read clients into memory.
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 2000,2006  The FreeRADIUS server project
21  * Copyright 2000  Miquel van Smoorenburg <miquels@cistron.nl>
22  * Copyright 2000  Alan DeKok <aland@ox.org>
23  */
24
25 #include <freeradius-devel/ident.h>
26 RCSID("$Id$")
27
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/rad_assert.h>
30
31 #include <sys/stat.h>
32
33 #include <ctype.h>
34 #include <fcntl.h>
35
36 #ifdef WITH_DYNAMIC_CLIENTS
37 #ifdef HAVE_DIRENT_H
38 #include <dirent.h>
39 #endif
40 #endif
41
42 struct radclient_list {
43         /*
44          *      FIXME: One set of trees for IPv4, and another for IPv6?
45          */
46         rbtree_t        *trees[129]; /* for 0..128, inclusive. */
47         int             min_prefix;
48 };
49
50
51 #ifdef WITH_STATS
52 static rbtree_t         *tree_num = NULL;     /* client numbers 0..N */
53 static int              tree_num_max = 0;
54 #endif
55 static RADCLIENT_LIST   *root_clients = NULL;
56
57 #ifdef WITH_DYNAMIC_CLIENTS
58 static fr_fifo_t        *deleted_clients = NULL;
59 #endif
60
61 /*
62  *      Callback for freeing a client.
63  */
64 void client_free(RADCLIENT *client)
65 {
66 #ifdef WITH_DYNAMIC_CLIENTS
67         if (client->dynamic == 2) {
68                 time_t now;
69
70                 if (!deleted_clients) {
71                         deleted_clients = fr_fifo_create(1024,
72                                                          (void *) client_free);
73                         if (!deleted_clients) return; /* MEMLEAK */
74                 }
75
76                 /*
77                  *      Mark it as in the fifo, and remember when we
78                  *      pushed it.
79                  */
80                 client->dynamic = 3;
81                 client->created = now = time(NULL); /* re-set it */
82                 fr_fifo_push(deleted_clients, client);
83
84                 /*
85                  *      Peek at the head of the fifo.  If it might
86                  *      still be in use, return.  Otherwise, pop it
87                  *      from the queue and delete it.
88                  */
89                 client = fr_fifo_peek(deleted_clients);
90                 if ((client->created + 120) >= now) return;
91
92                 client = fr_fifo_pop(deleted_clients);
93                 rad_assert(client != NULL);
94         }
95 #endif
96
97         free(client->longname);
98         free(client->secret);
99         free(client->shortname);
100         free(client->nastype);
101         free(client->login);
102         free(client->password);
103         free(client->server);
104
105 #ifdef WITH_STATS
106         free(client->auth);
107 #ifdef WITH_ACCOUNTING
108         free(client->acct);
109 #endif
110 #endif
111
112 #ifdef WITH_DYNAMIC_CLIENTS
113         free(client->client_server);
114 #endif
115
116         free(client);
117 }
118
119 /*
120  *      Callback for comparing two clients.
121  */
122 static int client_ipaddr_cmp(const void *one, const void *two)
123 {
124         const RADCLIENT *a = one;
125         const RADCLIENT *b = two;
126 #ifndef WITH_TCP
127
128         return fr_ipaddr_cmp(&a->ipaddr, &b->ipaddr);
129 #else
130         int rcode;
131
132         rcode = fr_ipaddr_cmp(&a->ipaddr, &b->ipaddr);
133         if (rcode != 0) return rcode;
134
135         /*
136          *      Wildcard match
137          */
138         if ((a->proto == IPPROTO_IP) ||
139             (b->proto == IPPROTO_IP)) return 0;
140
141         return (a->proto - b->proto);
142 #endif
143 }
144
145 #ifdef WITH_STATS
146 static int client_num_cmp(const void *one, const void *two)
147 {
148         const RADCLIENT *a = one;
149         const RADCLIENT *b = two;
150
151         return (a->number - b->number);
152 }
153 #endif
154
155 /*
156  *      Free a RADCLIENT list.
157  */
158 void clients_free(RADCLIENT_LIST *clients)
159 {
160         int i;
161
162         if (!clients) return;
163
164         for (i = 0; i <= 128; i++) {
165                 if (clients->trees[i]) rbtree_free(clients->trees[i]);
166                 clients->trees[i] = NULL;
167         }
168
169         if (clients == root_clients) {
170 #ifdef WITH_STATS
171                 if (tree_num) rbtree_free(tree_num);
172                 tree_num = NULL;
173                 tree_num_max = 0;
174 #endif
175                 root_clients = NULL;
176         }
177
178 #ifdef WITH_DYNAMIC_CLIENTS
179         /*
180          *      FIXME: No fr_fifo_delete()
181          */
182 #endif
183
184         free(clients);
185 }
186
187 /*
188  *      Return a new, initialized, set of clients.
189  */
190 RADCLIENT_LIST *clients_init(void)
191 {
192         RADCLIENT_LIST *clients = calloc(1, sizeof(RADCLIENT_LIST));
193
194         if (!clients) return NULL;
195
196         clients->min_prefix = 128;
197
198         return clients;
199 }
200
201
202 /*
203  *      Sanity check a client.
204  */
205 static int client_sane(RADCLIENT *client)
206 {
207         switch (client->ipaddr.af) {
208         case AF_INET:
209                 if (client->prefix > 32) {
210                         return 0;
211                 }
212
213                 /*
214                  *      Zero out the subnet bits.
215                  */
216                 if (client->prefix == 0) {
217                         memset(&client->ipaddr.ipaddr.ip4addr, 0,
218                                sizeof(client->ipaddr.ipaddr.ip4addr));
219
220                 } else if (client->prefix < 32) {
221                         uint32_t mask = ~0;
222
223                         mask <<= (32 - client->prefix);
224                         client->ipaddr.ipaddr.ip4addr.s_addr &= htonl(mask);
225                 }
226                 break;
227
228         case AF_INET6:
229                 if (client->prefix > 128) return 0;
230
231                 if (client->prefix == 0) {
232                         memset(&client->ipaddr.ipaddr.ip6addr, 0,
233                                sizeof(client->ipaddr.ipaddr.ip6addr));
234
235                 } else if (client->prefix < 128) {
236                         uint32_t mask, *addr;
237
238                         addr = (uint32_t *) &client->ipaddr.ipaddr.ip6addr;
239
240                         if ((client->prefix & 0x1f) == 0) {
241                                 mask = 0;
242                         } else {
243                                 mask = ~ ((uint32_t) 0);
244                                 mask <<= (32 - (client->prefix & 0x1f));
245                                 mask = htonl(mask);
246                         }
247
248                         switch (client->prefix >> 5) {
249                         case 0:
250                                 addr[0] &= mask;
251                                 mask = 0;
252                                 /* FALL-THROUGH */
253                         case 1:
254                                 addr[1] &= mask;
255                                 mask = 0;
256                                 /* FALL-THROUGH */
257                         case 2:
258                                 addr[2] &= mask;
259                                 mask = 0;
260                                 /* FALL-THROUGH */
261                         case 3:
262                                 addr[3] &= mask;
263                           break;
264                         }
265                 }
266                 break;
267
268         default:
269                 return 0;
270         }
271
272         return 1;
273 }
274
275
276 /*
277  *      Add a client to the tree.
278  */
279 int client_add(RADCLIENT_LIST *clients, RADCLIENT *client)
280 {
281         RADCLIENT *old;
282
283         if (!client) {
284                 return 0;
285         }
286
287         /*
288          *      If "clients" is NULL, it means add to the global list.
289          */
290         if (!clients) {
291                 /*
292                  *      Initialize it, if not done already.
293                  */
294                 if (!root_clients) {
295                         root_clients = clients_init();
296                         if (!root_clients) return 0;
297                 }
298                 clients = root_clients;
299         }
300
301         if ((client->prefix < 0) || (client->prefix > 128)) {
302                 return 0;
303         }
304
305         if (!client_sane(client)) return 0;
306
307         /*
308          *      Create a tree for it.
309          */
310         if (!clients->trees[client->prefix]) {
311                 clients->trees[client->prefix] = rbtree_create(client_ipaddr_cmp,
312                                                                (void *) client_free, 0);
313                 if (!clients->trees[client->prefix]) {
314                         return 0;
315                 }
316         }
317
318 #define namecmp(a) ((!old->a && !client->a) || (old->a && client->a && (strcmp(old->a, client->a) == 0)))
319
320         /*
321          *      Cannot insert the same client twice.
322          */
323         old = rbtree_finddata(clients->trees[client->prefix], client);
324         if (old) {
325                 /*
326                  *      If it's a complete duplicate, then free the new
327                  *      one, and return "OK".
328                  */
329                 if ((fr_ipaddr_cmp(&old->ipaddr, &client->ipaddr) == 0) &&
330                     (old->prefix == client->prefix) &&
331                     namecmp(longname) && namecmp(secret) &&
332                     namecmp(shortname) && namecmp(nastype) &&
333                     namecmp(login) && namecmp(password) && namecmp(server) &&
334 #ifdef WITH_DYNAMIC_CLIENTS
335                     (old->lifetime == client->lifetime) &&
336                     namecmp(client_server) &&
337 #endif
338 #ifdef WITH_COA
339                     namecmp(coa_name) &&
340                     (old->coa_server == client->coa_server) &&
341                     (old->coa_pool == client->coa_pool) &&
342 #endif
343                     (old->message_authenticator == client->message_authenticator)) {
344                         DEBUG("WARNING: Ignoring duplicate client %s", client->longname);
345                         client_free(client);
346                         return 1;
347                 }
348
349                 radlog(L_ERR, "Failed to add duplicate client %s",
350                        client->shortname);
351                 return 0;
352         }
353 #undef namecmp
354
355         /*
356          *      Other error adding client: likely is fatal.
357          */
358         if (!rbtree_insert(clients->trees[client->prefix], client)) {
359                 return 0;
360         }
361
362 #ifdef WITH_STATS
363         if (!tree_num) {
364                 tree_num = rbtree_create(client_num_cmp, NULL, 0);
365         }
366
367
368         /*
369          *      Catch clients added by rlm_sql.
370          */
371         if (!client->auth) {
372                 client->auth = rad_malloc(sizeof(*client->auth));
373                 memset(client->auth, 0, sizeof(*client->auth));
374         }
375
376 #ifdef WITH_ACCOUNTING
377         if (!client->acct) {
378                 client->acct = rad_malloc(sizeof(*client->acct));
379                 memset(client->acct, 0, sizeof(*client->acct));
380         }
381 #endif
382
383 #ifdef WITH_DYNAMIC_CLIENTS
384         /*
385          *      More catching of clients added by rlm_sql.
386          *
387          *      The sql modules sets the dynamic flag BEFORE calling
388          *      us.  The client_create() function sets it AFTER
389          *      calling us.
390          */
391         if (client->dynamic && (client->lifetime == 0)) {
392                 RADCLIENT *network;
393
394                 /*
395                  *      If there IS an enclosing network,
396                  *      inherit the lifetime from it.
397                  */
398                 network = client_find(clients, &client->ipaddr, client->proto);
399                 if (network) {
400                         client->lifetime = network->lifetime;
401                 }
402         }
403 #endif
404
405         client->number = tree_num_max;
406         tree_num_max++;
407         if (tree_num) rbtree_insert(tree_num, client);
408 #endif
409
410         if (client->prefix < clients->min_prefix) {
411                 clients->min_prefix = client->prefix;
412         }
413
414         return 1;
415 }
416
417
418 #ifdef WITH_DYNAMIC_CLIENTS
419 void client_delete(RADCLIENT_LIST *clients, RADCLIENT *client)
420 {
421         if (!client) return;
422
423         if (!clients) clients = root_clients;
424
425         if (!client->dynamic) return;
426
427         rad_assert((client->prefix >= 0) && (client->prefix <= 128));
428
429         client->dynamic = 2;    /* signal to client_free */
430
431         rbtree_deletebydata(tree_num, client);
432         rbtree_deletebydata(clients->trees[client->prefix], client);
433 }
434 #endif
435
436
437 /*
438  *      Find a client in the RADCLIENTS list by number.
439  *      This is a support function for the statistics code.
440  */
441 RADCLIENT *client_findbynumber(const RADCLIENT_LIST *clients,
442                                int number)
443 {
444 #ifdef WITH_STATS
445         if (!clients) clients = root_clients;
446
447         if (!clients) return NULL;
448
449         if (number >= tree_num_max) return NULL;
450
451         if (tree_num) {
452                 RADCLIENT myclient;
453
454                 myclient.number = number;
455
456                 return rbtree_finddata(tree_num, &myclient);
457         }
458 #else
459         clients = clients;      /* -Wunused */
460         number = number;        /* -Wunused */
461 #endif
462         return NULL;
463 }
464
465
466 /*
467  *      Find a client in the RADCLIENTS list.
468  */
469 RADCLIENT *client_find(const RADCLIENT_LIST *clients,
470                        const fr_ipaddr_t *ipaddr, int proto)
471 {
472         int i, max_prefix;
473         RADCLIENT myclient;
474
475         if (!clients) clients = root_clients;
476
477         if (!clients || !ipaddr) return NULL;
478
479         switch (ipaddr->af) {
480         case AF_INET:
481                 max_prefix = 32;
482                 break;
483
484         case AF_INET6:
485                 max_prefix = 128;
486                 break;
487
488         default :
489                 return NULL;
490         }
491
492         for (i = max_prefix; i >= clients->min_prefix; i--) {
493                 void *data;
494
495                 myclient.prefix = i;
496                 myclient.ipaddr = *ipaddr;
497                 myclient.proto = proto;
498                 client_sane(&myclient); /* clean up the ipaddress */
499
500                 if (!clients->trees[i]) continue;
501
502                 data = rbtree_finddata(clients->trees[i], &myclient);
503                 if (data) {
504                         return data;
505                 }
506         }
507
508         return NULL;
509 }
510
511
512 /*
513  *      Old wrapper for client_find
514  */
515 RADCLIENT *client_find_old(const fr_ipaddr_t *ipaddr)
516 {
517         return client_find(root_clients, ipaddr, IPPROTO_UDP);
518 }
519
520 static struct in_addr cl_ip4addr;
521 static struct in6_addr cl_ip6addr;
522 #ifdef WITH_TCP
523 static char *hs_proto = NULL;
524 #endif
525
526 static const CONF_PARSER client_config[] = {
527         { "ipaddr",  PW_TYPE_IPADDR,
528           0, &cl_ip4addr,  NULL },
529         { "ipv6addr",  PW_TYPE_IPV6ADDR,
530           0, &cl_ip6addr, NULL },
531         { "netmask",  PW_TYPE_INTEGER,
532           offsetof(RADCLIENT, prefix), 0, NULL },
533
534         { "require_message_authenticator",  PW_TYPE_BOOLEAN,
535           offsetof(RADCLIENT, message_authenticator), 0, "no" },
536
537         { "secret",  PW_TYPE_STRING_PTR,
538           offsetof(RADCLIENT, secret), 0, NULL },
539         { "shortname",  PW_TYPE_STRING_PTR,
540           offsetof(RADCLIENT, shortname), 0, NULL },
541         { "nastype",  PW_TYPE_STRING_PTR,
542           offsetof(RADCLIENT, nastype), 0, NULL },
543         { "login",  PW_TYPE_STRING_PTR,
544           offsetof(RADCLIENT, login), 0, NULL },
545         { "password",  PW_TYPE_STRING_PTR,
546           offsetof(RADCLIENT, password), 0, NULL },
547         { "virtual_server",  PW_TYPE_STRING_PTR,
548           offsetof(RADCLIENT, server), 0, NULL },
549         { "server",  PW_TYPE_STRING_PTR, /* compatability with 2.0-pre */
550           offsetof(RADCLIENT, server), 0, NULL },
551
552 #ifdef WITH_TCP
553         { "proto",  PW_TYPE_STRING_PTR,
554           0, &hs_proto, NULL },
555         { "max_connections",  PW_TYPE_INTEGER,
556           offsetof(RADCLIENT, max_connections), 0, "16" },
557 #endif
558
559 #ifdef WITH_DYNAMIC_CLIENTS
560         { "dynamic_clients",  PW_TYPE_STRING_PTR,
561           offsetof(RADCLIENT, client_server), 0, NULL },
562         { "lifetime",  PW_TYPE_INTEGER,
563           offsetof(RADCLIENT, lifetime), 0, NULL },
564         { "rate_limit",  PW_TYPE_BOOLEAN,
565           offsetof(RADCLIENT, rate_limit), 0, NULL },
566 #endif
567
568 #ifdef WITH_COA
569         { "coa_server",  PW_TYPE_STRING_PTR,
570           offsetof(RADCLIENT, coa_name), 0, NULL },
571 #endif
572
573         { NULL, -1, 0, NULL, NULL }
574 };
575
576
577 static RADCLIENT *client_parse(CONF_SECTION *cs, int in_server)
578 {
579         RADCLIENT       *c;
580         const char      *name2;
581
582         name2 = cf_section_name2(cs);
583         if (!name2) {
584                 cf_log_err(cf_sectiontoitem(cs),
585                            "Missing client name");
586                 return NULL;
587         }
588
589         /*
590          * The size is fine.. Let's create the buffer
591          */
592         c = rad_malloc(sizeof(*c));
593         memset(c, 0, sizeof(*c));
594         c->cs = cs;
595
596 #ifdef WITH_STATS
597         c->auth = rad_malloc(sizeof(*c->auth));
598         memset(c->auth, 0, sizeof(*c->auth));
599
600 #ifdef WITH_ACCOUNTING
601         c->acct = rad_malloc(sizeof(*c->acct));
602         memset(c->acct, 0, sizeof(*c->acct));
603 #endif
604 #endif
605
606         memset(&cl_ip4addr, 0, sizeof(cl_ip4addr));
607         memset(&cl_ip6addr, 0, sizeof(cl_ip6addr));
608         c->prefix = -1;
609
610         if (cf_section_parse(cs, c, client_config) < 0) {
611                 cf_log_err(cf_sectiontoitem(cs),
612                            "Error parsing client section.");
613         error:
614                 client_free(c);
615 #ifdef WITH_TCP
616                 free(hs_proto);
617                 hs_proto = NULL;
618 #endif
619
620                 return NULL;
621         }
622
623         /*
624          *      Global clients can set servers to use,
625          *      per-server clients cannot.
626          */
627         if (in_server && c->server) {
628                 cf_log_err(cf_sectiontoitem(cs),
629                            "Clients inside of an server section cannot point to a server.");
630                 goto error;
631         }
632                 
633         /*
634          *      No "ipaddr" or "ipv6addr", use old-style
635          *      "client <ipaddr> {" syntax.
636          */
637         if (!cf_pair_find(cs, "ipaddr") &&
638             !cf_pair_find(cs, "ipv6addr")) {
639                 char *prefix_ptr;
640
641                 prefix_ptr = strchr(name2, '/');
642
643                 /*
644                  *      Look for prefixes.
645                  */
646                 if (prefix_ptr) {
647                         c->prefix = atoi(prefix_ptr + 1);
648                         if ((c->prefix < 0) || (c->prefix > 128)) {
649                                 cf_log_err(cf_sectiontoitem(cs),
650                                            "Invalid Prefix value '%s' for IP.",
651                                            prefix_ptr + 1);
652                                 goto error;
653                         }
654                         /* Replace '/' with '\0' */
655                         *prefix_ptr = '\0';
656                 }
657                         
658                 /*
659                  *      Always get the numeric representation of IP
660                  */
661                 if (ip_hton(name2, AF_UNSPEC, &c->ipaddr) < 0) {
662                         cf_log_err(cf_sectiontoitem(cs),
663                                    "Failed to look up hostname %s: %s",
664                                    name2, fr_strerror());
665                         goto error;
666                 }
667
668                 if (prefix_ptr) *prefix_ptr = '/';
669                 c->longname = strdup(name2);
670
671                 if (!c->shortname) c->shortname = strdup(c->longname);
672
673         } else {
674                 char buffer[1024];
675
676                 /*
677                  *      Figure out which one to use.
678                  */
679                 if (cf_pair_find(cs, "ipaddr")) {
680                         c->ipaddr.af = AF_INET;
681                         c->ipaddr.ipaddr.ip4addr = cl_ip4addr;
682
683                         if ((c->prefix < -1) || (c->prefix > 32)) {
684                                 cf_log_err(cf_sectiontoitem(cs),
685                                            "Netmask must be between 0 and 32");
686                                 goto error;
687                         }
688                                 
689                 } else if (cf_pair_find(cs, "ipv6addr")) {
690                         c->ipaddr.af = AF_INET6;
691                         c->ipaddr.ipaddr.ip6addr = cl_ip6addr;
692                                 
693                         if ((c->prefix < -1) || (c->prefix > 128)) {
694                                 cf_log_err(cf_sectiontoitem(cs),
695                                            "Netmask must be between 0 and 128");
696                                 goto error;
697                         }
698                 } else {
699                         cf_log_err(cf_sectiontoitem(cs),
700                                    "No IP address defined for the client");
701                         goto error;
702                 }
703
704                 ip_ntoh(&c->ipaddr, buffer, sizeof(buffer));
705                 c->longname = strdup(buffer);
706
707                 /*
708                  *      Set the short name to the name2
709                  */
710                 if (!c->shortname) c->shortname = strdup(name2);
711
712                 c->proto = IPPROTO_UDP;
713 #ifdef WITH_TCP
714                 if (hs_proto) {
715                         if (strcmp(hs_proto, "udp") == 0) {
716                                 free(hs_proto);
717                                 hs_proto = NULL;
718                                 
719                         } else if (strcmp(hs_proto, "tcp") == 0) {
720                                 free(hs_proto);
721                                 hs_proto = NULL;
722                                 c->proto = IPPROTO_TCP;
723                                 
724                         } else if (strcmp(hs_proto, "*") == 0) {
725                                 free(hs_proto);
726                                 hs_proto = NULL;
727                                 c->proto = IPPROTO_IP; /* fake for dual */
728                                 
729                         } else {
730                                 cf_log_err(cf_sectiontoitem(cs),
731                                            "Unknown proto \"%s\".", hs_proto);
732                                 goto error;
733                         }
734                 }
735 #endif
736         }
737
738         if (c->prefix < 0) switch (c->ipaddr.af) {
739         case AF_INET:
740                 c->prefix = 32;
741                 break;
742         case AF_INET6:
743                 c->prefix = 128;
744                 break;
745         default:
746                 break;
747         }
748
749 #ifdef WITH_DYNAMIC_CLIENTS
750         if (c->client_server) {
751                 free(c->secret);
752                 c->secret = strdup("testing123");
753
754                 if (((c->ipaddr.af == AF_INET) &&
755                      (c->prefix == 32)) ||
756                     ((c->ipaddr.af == AF_INET6) &&
757                      (c->prefix == 128))) {
758                         cf_log_err(cf_sectiontoitem(cs),
759                                    "Dynamic clients MUST be a network, not a single IP address.");
760                         goto error;
761                 }
762
763                 return c;
764         }
765 #endif
766
767         if (!c->secret || !*c->secret) {
768 #ifdef WITH_DHCP
769                 const char *value = NULL;
770                 CONF_PAIR *cp = cf_pair_find(cs, "dhcp");
771
772                 if (cp) value = cf_pair_value(cp);
773
774                 /*
775                  *      Secrets aren't needed for DHCP.
776                  */
777                 if (value && (strcmp(value, "yes") == 0)) return c;
778
779 #endif
780                 cf_log_err(cf_sectiontoitem(cs),
781                            "secret must be at least 1 character long");
782                 goto error;
783         }
784
785 #ifdef WITH_COA
786         /*
787          *      Point the client to the home server pool, OR to the
788          *      home server.  This gets around the problem of figuring
789          *      out which port to use.
790          */
791         if (c->coa_name) {
792                 c->coa_pool = home_pool_byname(c->coa_name, HOME_TYPE_COA);
793                 if (!c->coa_pool) {
794                         c->coa_server = home_server_byname(c->coa_name,
795                                                            HOME_TYPE_COA);
796                 }
797                 if (!c->coa_pool && !c->coa_server) {
798                         cf_log_err(cf_sectiontoitem(cs), "No such home_server or home_server_pool \"%s\"", c->coa_name);
799                         goto error;
800                 }
801         }
802 #endif
803
804         return c;
805 }
806
807
808 /*
809  *      Create the linked list of clients from the new configuration
810  *      type.  This way we don't have to change too much in the other
811  *      source-files.
812  */
813 RADCLIENT_LIST *clients_parse_section(CONF_SECTION *section)
814 {
815         int             global = FALSE, in_server = FALSE;
816         CONF_SECTION    *cs;
817         RADCLIENT       *c;
818         RADCLIENT_LIST  *clients;
819
820         /*
821          *      Be forgiving.  If there's already a clients, return
822          *      it.  Otherwise create a new one.
823          */
824         clients = cf_data_find(section, "clients");
825         if (clients) return clients;
826
827         clients = clients_init();
828         if (!clients) return NULL;
829
830         if (cf_top_section(section) == section) global = TRUE;
831
832         if (strcmp("server", cf_section_name1(section)) == 0) in_server = TRUE;
833
834         /*
835          *      Associate the clients structure with the section, where
836          *      it will be freed once the section is freed.
837          */
838         if (cf_data_add(section, "clients", clients, (void *) clients_free) < 0) {
839                 cf_log_err(cf_sectiontoitem(section),
840                            "Failed to associate clients with section %s",
841                        cf_section_name1(section));
842                 clients_free(clients);
843                 return NULL;
844         }
845
846         for (cs = cf_subsection_find_next(section, NULL, "client");
847              cs != NULL;
848              cs = cf_subsection_find_next(section, cs, "client")) {
849                 c = client_parse(cs, in_server);
850                 if (!c) {
851                         return NULL;
852                 }
853
854                 /*
855                  *      FIXME: Add the client as data via cf_data_add,
856                  *      for migration issues.
857                  */
858
859 #ifdef WITH_DYNAMIC_CLIENTS
860 #ifdef HAVE_DIRENT_H
861                 if (c->client_server) {
862                         const char *value;
863                         CONF_PAIR *cp;
864                         DIR             *dir;
865                         struct dirent   *dp;
866                         struct stat stat_buf;
867                         char buf2[2048];
868
869                         /*
870                          *      Find the directory where individual
871                          *      client definitions are stored.
872                          */
873                         cp = cf_pair_find(cs, "directory");
874                         if (!cp) goto add_client;
875                         
876                         value = cf_pair_value(cp);
877                         if (!value) {
878                                 cf_log_err(cf_sectiontoitem(cs),
879                                            "The \"directory\" entry must not be empty");
880                                 client_free(c);
881                                 return NULL;
882                         }
883
884                         DEBUG("including dynamic clients in %s", value);
885                         
886                         dir = opendir(value);
887                         if (!dir) {
888                                 cf_log_err(cf_sectiontoitem(cs), "Error reading directory %s: %s", value, strerror(errno));
889                                 client_free(c);
890                                 return NULL;
891                         }
892                         
893                         /*
894                          *      Read the directory, ignoring "." files.
895                          */
896                         while ((dp = readdir(dir)) != NULL) {
897                                 const char *p;
898                                 RADCLIENT *dc;
899
900                                 if (dp->d_name[0] == '.') continue;
901
902                                 /*
903                                  *      Check for valid characters
904                                  */
905                                 for (p = dp->d_name; *p != '\0'; p++) {
906                                         if (isalpha((int)*p) ||
907                                             isdigit((int)*p) ||
908                                             (*p == ':') ||
909                                             (*p == '.')) continue;
910                                                 break;
911                                 }
912                                 if (*p != '\0') continue;
913
914                                 snprintf(buf2, sizeof(buf2), "%s/%s",
915                                          value, dp->d_name);
916
917                                 if ((stat(buf2, &stat_buf) != 0) ||
918                                     S_ISDIR(stat_buf.st_mode)) continue;
919
920                                 dc = client_read(buf2, in_server, TRUE);
921                                 if (!dc) {
922                                         cf_log_err(cf_sectiontoitem(cs),
923                                                    "Failed reading client file \"%s\"", buf2);
924                                         client_free(c);
925                                         return NULL;
926                                 }
927
928                                 /*
929                                  *      Validate, and add to the list.
930                                  */
931                                 if (!client_validate(clients, c, dc)) {
932                                         
933                                         client_free(c);
934                                         return NULL;
935                                 }
936                         } /* loop over the directory */
937                 }
938 #endif /* HAVE_DIRENT_H */
939 #endif /* WITH_DYNAMIC_CLIENTS */
940
941         add_client:
942                 if (!client_add(clients, c)) {
943                         cf_log_err(cf_sectiontoitem(cs),
944                                    "Failed to add client %s",
945                                    cf_section_name2(cs));
946                         client_free(c);
947                         return NULL;
948                 }
949
950         }
951
952         /*
953          *      Replace the global list of clients with the new one.
954          *      The old one is still referenced from the original
955          *      configuration, and will be freed when that is freed.
956          */
957         if (global) {
958                 root_clients = clients;
959         }
960
961         return clients;
962 }
963
964 #ifdef WITH_DYNAMIC_CLIENTS
965 /*
966  *      We overload this structure a lot.
967  */
968 static const CONF_PARSER dynamic_config[] = {
969         { "FreeRADIUS-Client-IP-Address",  PW_TYPE_IPADDR,
970           offsetof(RADCLIENT, ipaddr), 0, NULL },
971         { "FreeRADIUS-Client-IPv6-Address",  PW_TYPE_IPV6ADDR,
972           offsetof(RADCLIENT, ipaddr), 0, NULL },
973
974         { "FreeRADIUS-Client-Require-MA",  PW_TYPE_BOOLEAN,
975           offsetof(RADCLIENT, message_authenticator), NULL, NULL },
976
977         { "FreeRADIUS-Client-Secret",  PW_TYPE_STRING_PTR,
978           offsetof(RADCLIENT, secret), 0, "" },
979         { "FreeRADIUS-Client-Shortname",  PW_TYPE_STRING_PTR,
980           offsetof(RADCLIENT, shortname), 0, "" },
981         { "FreeRADIUS-Client-NAS-Type",  PW_TYPE_STRING_PTR,
982           offsetof(RADCLIENT, nastype), 0, NULL },
983         { "FreeRADIUS-Client-Virtual-Server",  PW_TYPE_STRING_PTR,
984           offsetof(RADCLIENT, server), 0, NULL },
985
986         { NULL, -1, 0, NULL, NULL }
987 };
988
989
990 int client_validate(RADCLIENT_LIST *clients, RADCLIENT *master, RADCLIENT *c)
991 {
992         char buffer[128];
993
994         /*
995          *      No virtual server defined.  Inherit the parent's
996          *      definition.
997          */
998         if (master->server && !c->server) {
999                 c->server = strdup(master->server);
1000         }
1001
1002         /*
1003          *      If the client network isn't global (not tied to a
1004          *      virtual server), then ensure that this clients server
1005          *      is the same as the enclosing networks virtual server.
1006          */
1007         if (master->server &&
1008              (strcmp(master->server, c->server) != 0)) {
1009                 DEBUG("- Cannot add client %s: Virtual server %s is not the same as the virtual server for the network.",
1010                       ip_ntoh(&c->ipaddr,
1011                               buffer, sizeof(buffer)),
1012                       c->server);
1013
1014                 goto error;
1015         }
1016
1017         if (!client_add(clients, c)) {
1018                 DEBUG("- Cannot add client %s: Internal error",
1019                       ip_ntoh(&c->ipaddr,
1020                               buffer, sizeof(buffer)));
1021
1022                 goto error;
1023         }
1024
1025         /*
1026          *      Initialize the remaining fields.
1027          */
1028         c->dynamic = TRUE;
1029         c->lifetime = master->lifetime;
1030         c->created = time(NULL);
1031         c->longname = strdup(c->shortname);
1032
1033         DEBUG("- Added client %s with shared secret %s",
1034               ip_ntoh(&c->ipaddr, buffer, sizeof(buffer)),
1035               c->secret);
1036
1037         return 1;
1038
1039  error:
1040         client_free(c);
1041         return 0;
1042 }
1043
1044
1045 RADCLIENT *client_create(RADCLIENT_LIST *clients, REQUEST *request)
1046 {
1047         int i, *pi;
1048         char **p;
1049         RADCLIENT *c;
1050         char buffer[128];
1051
1052         if (!clients || !request) return NULL;
1053
1054         c = rad_malloc(sizeof(*c));
1055         memset(c, 0, sizeof(*c));
1056         c->cs = request->client->cs;
1057         c->ipaddr.af = AF_UNSPEC;
1058
1059         for (i = 0; dynamic_config[i].name != NULL; i++) {
1060                 DICT_ATTR *da;
1061                 VALUE_PAIR *vp;
1062
1063                 da = dict_attrbyname(dynamic_config[i].name);
1064                 if (!da) {
1065                         DEBUG("- Cannot add client %s: attribute \"%s\"is not in the dictionary",
1066                               ip_ntoh(&request->packet->src_ipaddr,
1067                                       buffer, sizeof(buffer)),
1068                               dynamic_config[i].name);
1069                 error:
1070                         client_free(c);
1071                         return NULL;
1072                 }
1073
1074                 vp = pairfind(request->config_items, da->attr, da->vendor);
1075                 if (!vp) {
1076                         /*
1077                          *      Not required.  Skip it.
1078                          */
1079                         if (!dynamic_config[i].dflt) continue;
1080                         
1081                         DEBUG("- Cannot add client %s: Required attribute \"%s\" is missing.",  
1082                               ip_ntoh(&request->packet->src_ipaddr,
1083                                       buffer, sizeof(buffer)),
1084                               dynamic_config[i].name);
1085                         goto error;
1086                 }
1087
1088                 switch (dynamic_config[i].type) {
1089                 case PW_TYPE_IPADDR:
1090                         c->ipaddr.af = AF_INET;
1091                         c->ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1092                         c->prefix = 32;
1093                         break;
1094
1095                 case PW_TYPE_IPV6ADDR:
1096                         c->ipaddr.af = AF_INET6;
1097                         c->ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1098                         c->prefix = 128;
1099                         break;
1100
1101                 case PW_TYPE_STRING_PTR:
1102                         p = (char **) ((char *) c + dynamic_config[i].offset);
1103                         if (*p) free(*p);
1104                         *p = strdup(vp->vp_strvalue);
1105                         break;
1106
1107                 case PW_TYPE_BOOLEAN:
1108                         pi = (int *) ((char *) c + dynamic_config[i].offset);
1109                         *pi = vp->vp_integer;
1110                         break;
1111
1112                 default:
1113                         goto error;
1114                 }
1115         }
1116
1117         if (c->ipaddr.af == AF_UNSPEC) {
1118                 DEBUG("- Cannot add client %s: No IP address was specified.",
1119                       ip_ntoh(&request->packet->src_ipaddr,
1120                               buffer, sizeof(buffer)));
1121
1122                 goto error;
1123         }
1124
1125         if (fr_ipaddr_cmp(&request->packet->src_ipaddr, &c->ipaddr) != 0) {
1126                 char buf2[128];
1127
1128                 DEBUG("- Cannot add client %s: IP address %s do not match",
1129                       ip_ntoh(&request->packet->src_ipaddr,
1130                               buffer, sizeof(buffer)),
1131                       ip_ntoh(&c->ipaddr,
1132                               buf2, sizeof(buf2)));                   
1133                 goto error;
1134         }
1135
1136         if (!client_validate(clients, request->client, c)) {
1137                 return NULL;
1138         }
1139
1140         return c;
1141 }
1142
1143 /*
1144  *      Read a client definition from the given filename.
1145  */
1146 RADCLIENT *client_read(const char *filename, int in_server, int flag)
1147 {
1148         const char *p;
1149         RADCLIENT *c;
1150         CONF_SECTION *cs;
1151         char buffer[256];
1152
1153         if (!filename) return NULL;
1154
1155         cs = cf_file_read(filename);
1156         if (!cs) return NULL;
1157
1158         c = client_parse(cf_section_sub_find(cs, "client"), in_server);
1159
1160         p = strrchr(filename, FR_DIR_SEP);
1161         if (p) {
1162                 p++;
1163         } else {
1164                 p = filename;
1165         }
1166
1167         if (!flag) return c;
1168
1169         /*
1170          *      Additional validations
1171          */
1172         ip_ntoh(&c->ipaddr, buffer, sizeof(buffer));
1173         if (strcmp(p, buffer) != 0) {
1174                 DEBUG("Invalid client definition in %s: IP address %s does not match name %s", filename, buffer, p);
1175                 client_free(c);
1176                 return NULL;
1177         }
1178
1179
1180
1181         return c;
1182 }
1183 #endif