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