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