Allow clients to use TCP
[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                         int i;
237                         uint32_t mask, *addr;
238
239                         addr = (uint32_t *) &client->ipaddr.ipaddr.ip6addr;
240
241                         for (i = client->prefix; i < 128; i += 32) {
242                                 mask = ~0;
243                                 mask <<= ((128 - i) & 0x1f);
244                                 addr[i / 32] &= mask;
245                         }
246                 }
247                 break;
248
249         default:
250                 return 0;
251         }
252
253         return 1;
254 }
255
256
257 /*
258  *      Add a client to the tree.
259  */
260 int client_add(RADCLIENT_LIST *clients, RADCLIENT *client)
261 {
262         RADCLIENT *old;
263
264         if (!client) {
265                 return 0;
266         }
267
268         /*
269          *      If "clients" is NULL, it means add to the global list.
270          */
271         if (!clients) {
272                 /*
273                  *      Initialize it, if not done already.
274                  */
275                 if (!root_clients) {
276                         root_clients = clients_init();
277                         if (!root_clients) return 0;
278                 }
279                 clients = root_clients;
280         }
281
282         if ((client->prefix < 0) || (client->prefix > 128)) {
283                 return 0;
284         }
285
286         if (!client_sane(client)) return 0;
287
288         /*
289          *      Create a tree for it.
290          */
291         if (!clients->trees[client->prefix]) {
292                 clients->trees[client->prefix] = rbtree_create(client_ipaddr_cmp,
293                                                                (void *) client_free, 0);
294                 if (!clients->trees[client->prefix]) {
295                         return 0;
296                 }
297         }
298
299 #define namecmp(a) ((!old->a && !client->a) || (old->a && client->a && (strcmp(old->a, client->a) == 0)))
300
301         /*
302          *      Cannot insert the same client twice.
303          */
304         old = rbtree_finddata(clients->trees[client->prefix], client);
305         if (old) {
306                 /*
307                  *      If it's a complete duplicate, then free the new
308                  *      one, and return "OK".
309                  */
310                 if ((fr_ipaddr_cmp(&old->ipaddr, &client->ipaddr) == 0) &&
311                     (old->prefix == client->prefix) &&
312                     namecmp(longname) && namecmp(secret) &&
313                     namecmp(shortname) && namecmp(nastype) &&
314                     namecmp(login) && namecmp(password) && namecmp(server) &&
315 #ifdef WITH_DYNAMIC_CLIENTS
316                     (old->lifetime == client->lifetime) &&
317                     namecmp(client_server) &&
318 #endif
319 #ifdef WITH_COA
320                     namecmp(coa_name) &&
321                     (old->coa_server == client->coa_server) &&
322                     (old->coa_pool == client->coa_pool) &&
323 #endif
324                     (old->message_authenticator == client->message_authenticator)) {
325                         DEBUG("WARNING: Ignoring duplicate client %s", client->longname);
326                         client_free(client);
327                         return 1;
328                 }
329
330                 radlog(L_ERR, "Failed to add duplicate client %s",
331                        client->shortname);
332                 return 0;
333         }
334 #undef namecmp
335
336         /*
337          *      Other error adding client: likely is fatal.
338          */
339         if (!rbtree_insert(clients->trees[client->prefix], client)) {
340                 return 0;
341         }
342
343 #ifdef WITH_STATS
344         if (!tree_num) {
345                 tree_num = rbtree_create(client_num_cmp, NULL, 0);
346         }
347
348
349         /*
350          *      Catch clients added by rlm_sql.
351          */
352         if (!client->auth) {
353                 client->auth = rad_malloc(sizeof(*client->auth));
354                 memset(client->auth, 0, sizeof(*client->auth));
355         }
356
357 #ifdef WITH_ACCOUNTING
358         if (!client->acct) {
359                 client->acct = rad_malloc(sizeof(*client->acct));
360                 memset(client->acct, 0, sizeof(*client->acct));
361         }
362 #endif
363
364 #ifdef WITH_DYNAMIC_CLIENTS
365         /*
366          *      More catching of clients added by rlm_sql.
367          *
368          *      The sql modules sets the dynamic flag BEFORE calling
369          *      us.  The client_create() function sets it AFTER
370          *      calling us.
371          */
372         if (client->dynamic && (client->lifetime == 0)) {
373                 RADCLIENT *network;
374
375                 /*
376                  *      If there IS an enclosing network,
377                  *      inherit the lifetime from it.
378                  */
379                 network = client_find(clients, &client->ipaddr
380 #ifdef WITH_TCP
381                                       , client->proto
382 #endif
383                         );
384                 if (network) {
385                         client->lifetime = network->lifetime;
386                 }
387         }
388 #endif
389
390         client->number = tree_num_max;
391         tree_num_max++;
392         if (tree_num) rbtree_insert(tree_num, client);
393 #endif
394
395         if (client->prefix < clients->min_prefix) {
396                 clients->min_prefix = client->prefix;
397         }
398
399         return 1;
400 }
401
402
403 #ifdef WITH_DYNAMIC_CLIENTS
404 void client_delete(RADCLIENT_LIST *clients, RADCLIENT *client)
405 {
406         if (!clients || !client) return;
407
408         rad_assert((client->prefix >= 0) && (client->prefix <= 128));
409
410         client->dynamic = 2;    /* signal to client_free */
411
412         rbtree_deletebydata(tree_num, client);
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
452 #ifdef WITH_TCP
453                        , int proto
454 #endif
455         )
456 {
457         int i, max_prefix;
458         RADCLIENT myclient;
459
460         if (!clients) clients = root_clients;
461
462         if (!clients || !ipaddr) return NULL;
463
464         switch (ipaddr->af) {
465         case AF_INET:
466                 max_prefix = 32;
467                 break;
468
469         case AF_INET6:
470                 max_prefix = 128;
471                 break;
472
473         default :
474                 return NULL;
475         }
476
477         for (i = max_prefix; i >= clients->min_prefix; i--) {
478                 void *data;
479
480                 myclient.prefix = i;
481                 myclient.ipaddr = *ipaddr;
482 #ifdef WITH_TCP
483                 myclient.proto = proto;
484 #endif
485                 client_sane(&myclient); /* clean up the ipaddress */
486
487                 if (!clients->trees[i]) continue;
488
489                 data = rbtree_finddata(clients->trees[i], &myclient);
490                 if (data) {
491                         return data;
492                 }
493         }
494
495         return NULL;
496 }
497
498
499 /*
500  *      Old wrapper for client_find
501  */
502 RADCLIENT *client_find_old(const fr_ipaddr_t *ipaddr)
503 {
504         return client_find(root_clients, ipaddr, IPPROTO_UDP);
505 }
506
507 static struct in_addr cl_ip4addr;
508 static struct in6_addr cl_ip6addr;
509 #ifdef WITH_TCP
510 static char *hs_proto = NULL;
511 #endif
512
513 static const CONF_PARSER client_config[] = {
514         { "ipaddr",  PW_TYPE_IPADDR,
515           0, &cl_ip4addr,  NULL },
516         { "ipv6addr",  PW_TYPE_IPV6ADDR,
517           0, &cl_ip6addr, NULL },
518         { "netmask",  PW_TYPE_INTEGER,
519           offsetof(RADCLIENT, prefix), 0, NULL },
520
521         { "require_message_authenticator",  PW_TYPE_BOOLEAN,
522           offsetof(RADCLIENT, message_authenticator), 0, "no" },
523
524         { "secret",  PW_TYPE_STRING_PTR,
525           offsetof(RADCLIENT, secret), 0, NULL },
526         { "shortname",  PW_TYPE_STRING_PTR,
527           offsetof(RADCLIENT, shortname), 0, NULL },
528         { "nastype",  PW_TYPE_STRING_PTR,
529           offsetof(RADCLIENT, nastype), 0, NULL },
530         { "login",  PW_TYPE_STRING_PTR,
531           offsetof(RADCLIENT, login), 0, NULL },
532         { "password",  PW_TYPE_STRING_PTR,
533           offsetof(RADCLIENT, password), 0, NULL },
534         { "virtual_server",  PW_TYPE_STRING_PTR,
535           offsetof(RADCLIENT, server), 0, NULL },
536         { "server",  PW_TYPE_STRING_PTR, /* compatability with 2.0-pre */
537           offsetof(RADCLIENT, server), 0, NULL },
538
539 #ifdef WITH_TCP
540         { "proto",  PW_TYPE_STRING_PTR,
541           0, &hs_proto, NULL },
542         { "max_connections",  PW_TYPE_INTEGER,
543           offsetof(RADCLIENT, max_connections), 0, "16" },
544 #endif
545
546 #ifdef WITH_DYNAMIC_CLIENTS
547         { "dynamic_clients",  PW_TYPE_STRING_PTR,
548           offsetof(RADCLIENT, client_server), 0, NULL },
549         { "lifetime",  PW_TYPE_INTEGER,
550           offsetof(RADCLIENT, lifetime), 0, NULL },
551 #endif
552
553 #ifdef WITH_COA
554         { "coa_server",  PW_TYPE_STRING_PTR,
555           offsetof(RADCLIENT, coa_name), 0, NULL },
556 #endif
557
558         { NULL, -1, 0, NULL, NULL }
559 };
560
561
562 static RADCLIENT *client_parse(CONF_SECTION *cs, int in_server)
563 {
564         RADCLIENT       *c;
565         const char      *name2;
566
567         name2 = cf_section_name2(cs);
568         if (!name2) {
569                 cf_log_err(cf_sectiontoitem(cs),
570                            "Missing client name");
571                 return NULL;
572         }
573
574         /*
575          * The size is fine.. Let's create the buffer
576          */
577         c = rad_malloc(sizeof(*c));
578         memset(c, 0, sizeof(*c));
579         c->cs = cs;
580
581 #ifdef WITH_STATS
582         c->auth = rad_malloc(sizeof(*c->auth));
583         memset(c->auth, 0, sizeof(*c->auth));
584
585 #ifdef WITH_ACCOUNTING
586         c->acct = rad_malloc(sizeof(*c->acct));
587         memset(c->acct, 0, sizeof(*c->acct));
588 #endif
589 #endif
590
591         memset(&cl_ip4addr, 0, sizeof(cl_ip4addr));
592         memset(&cl_ip6addr, 0, sizeof(cl_ip6addr));
593         c->prefix = -1;
594
595         if (cf_section_parse(cs, c, client_config) < 0) {
596                 cf_log_err(cf_sectiontoitem(cs),
597                            "Error parsing client section.");
598         error:
599                 client_free(c);
600 #ifdef WITH_TCP
601                 free(hs_proto);
602                 hs_proto = NULL;
603 #endif
604
605                 return NULL;
606         }
607
608         /*
609          *      Global clients can set servers to use,
610          *      per-server clients cannot.
611          */
612         if (in_server && c->server) {
613                 cf_log_err(cf_sectiontoitem(cs),
614                            "Clients inside of an server section cannot point to a server.");
615                 goto error;
616         }
617                 
618         /*
619          *      No "ipaddr" or "ipv6addr", use old-style
620          *      "client <ipaddr> {" syntax.
621          */
622         if (!cf_pair_find(cs, "ipaddr") &&
623             !cf_pair_find(cs, "ipv6addr")) {
624                 char *prefix_ptr;
625
626                 prefix_ptr = strchr(name2, '/');
627
628                 /*
629                  *      Look for prefixes.
630                  */
631                 if (prefix_ptr) {
632                         c->prefix = atoi(prefix_ptr + 1);
633                         if ((c->prefix < 0) || (c->prefix > 128)) {
634                                 cf_log_err(cf_sectiontoitem(cs),
635                                            "Invalid Prefix value '%s' for IP.",
636                                            prefix_ptr + 1);
637                                 goto error;
638                         }
639                         /* Replace '/' with '\0' */
640                         *prefix_ptr = '\0';
641                 }
642                         
643                 /*
644                  *      Always get the numeric representation of IP
645                  */
646                 if (ip_hton(name2, AF_UNSPEC, &c->ipaddr) < 0) {
647                         cf_log_err(cf_sectiontoitem(cs),
648                                    "Failed to look up hostname %s: %s",
649                                    name2, fr_strerror());
650                         goto error;
651                 }
652
653                 if (prefix_ptr) *prefix_ptr = '/';
654                 c->longname = strdup(name2);
655
656                 if (!c->shortname) c->shortname = strdup(c->longname);
657
658         } else {
659                 char buffer[1024];
660
661                 /*
662                  *      Figure out which one to use.
663                  */
664                 if (cf_pair_find(cs, "ipaddr")) {
665                         c->ipaddr.af = AF_INET;
666                         c->ipaddr.ipaddr.ip4addr = cl_ip4addr;
667
668                         if ((c->prefix < -1) || (c->prefix > 32)) {
669                                 cf_log_err(cf_sectiontoitem(cs),
670                                            "Netmask must be between 0 and 32");
671                                 goto error;
672                         }
673                                 
674                 } else if (cf_pair_find(cs, "ipv6addr")) {
675                         c->ipaddr.af = AF_INET6;
676                         c->ipaddr.ipaddr.ip6addr = cl_ip6addr;
677                                 
678                         if ((c->prefix < -1) || (c->prefix > 128)) {
679                                 cf_log_err(cf_sectiontoitem(cs),
680                                            "Netmask must be between 0 and 128");
681                                 goto error;
682                         }
683                 } else {
684                         cf_log_err(cf_sectiontoitem(cs),
685                                    "No IP address defined for the client");
686                         goto error;
687                 }
688
689                 ip_ntoh(&c->ipaddr, buffer, sizeof(buffer));
690                 c->longname = strdup(buffer);
691
692                 /*
693                  *      Set the short name to the name2
694                  */
695                 if (!c->shortname) c->shortname = strdup(name2);
696
697 #ifdef WITH_TCP
698                 c->proto = IPPROTO_UDP;
699                 if (hs_proto) {
700                         if (strcmp(hs_proto, "udp") == 0) {
701                                 free(hs_proto);
702                                 hs_proto = NULL;
703                                 
704                         } else if (strcmp(hs_proto, "tcp") == 0) {
705                                 free(hs_proto);
706                                 hs_proto = NULL;
707                                 c->proto = IPPROTO_TCP;
708                                 
709                         } else if (strcmp(hs_proto, "*") == 0) {
710                                 free(hs_proto);
711                                 hs_proto = NULL;
712                                 c->proto = IPPROTO_IP; /* fake for dual */
713                                 
714                         } else {
715                                 cf_log_err(cf_sectiontoitem(cs),
716                                            "Unknown proto \"%s\".", hs_proto);
717                                 goto error;
718                         }
719                 }
720 #endif
721         }
722
723         if (c->prefix < 0) switch (c->ipaddr.af) {
724         case AF_INET:
725                 c->prefix = 32;
726                 break;
727         case AF_INET6:
728                 c->prefix = 128;
729                 break;
730         default:
731                 break;
732         }
733
734 #ifdef WITH_DYNAMIC_CLIENTS
735         if (c->client_server) {
736                 free(c->secret);
737                 c->secret = strdup("testing123");
738
739                 if (((c->ipaddr.af == AF_INET) &&
740                      (c->prefix == 32)) ||
741                     ((c->ipaddr.af == AF_INET6) &&
742                      (c->prefix == 128))) {
743                         cf_log_err(cf_sectiontoitem(cs),
744                                    "Dynamic clients MUST be a network, not a single IP address.");
745                         goto error;
746                 }
747
748                 return c;
749         }
750 #endif
751
752         if (!c->secret || !*c->secret) {
753 #ifdef WITH_DHCP
754                 const char *value = NULL;
755                 CONF_PAIR *cp = cf_pair_find(cs, "dhcp");
756
757                 if (cp) value = cf_pair_value(cp);
758
759                 /*
760                  *      Secrets aren't needed for DHCP.
761                  */
762                 if (value && (strcmp(value, "yes") == 0)) return c;
763
764 #endif
765                 cf_log_err(cf_sectiontoitem(cs),
766                            "secret must be at least 1 character long");
767                 goto error;
768         }
769
770 #ifdef WITH_COA
771         /*
772          *      Point the client to the home server pool, OR to the
773          *      home server.  This gets around the problem of figuring
774          *      out which port to use.
775          */
776         if (c->coa_name) {
777                 c->coa_pool = home_pool_byname(c->coa_name, HOME_TYPE_COA);
778                 if (!c->coa_pool) {
779                         c->coa_server = home_server_byname(c->coa_name,
780                                                            HOME_TYPE_COA);
781                 }
782                 if (!c->coa_pool && !c->coa_server) {
783                         cf_log_err(cf_sectiontoitem(cs), "No such home_server or home_server_pool \"%s\"", c->coa_name);
784                         goto error;
785                 }
786         }
787 #endif
788
789         return c;
790 }
791
792
793 /*
794  *      Create the linked list of clients from the new configuration
795  *      type.  This way we don't have to change too much in the other
796  *      source-files.
797  */
798 RADCLIENT_LIST *clients_parse_section(CONF_SECTION *section)
799 {
800         int             global = FALSE, in_server = FALSE;
801         CONF_SECTION    *cs;
802         RADCLIENT       *c;
803         RADCLIENT_LIST  *clients;
804
805         /*
806          *      Be forgiving.  If there's already a clients, return
807          *      it.  Otherwise create a new one.
808          */
809         clients = cf_data_find(section, "clients");
810         if (clients) return clients;
811
812         clients = clients_init();
813         if (!clients) return NULL;
814
815         if (cf_top_section(section) == section) global = TRUE;
816
817         if (strcmp("server", cf_section_name1(section)) == 0) in_server = TRUE;
818
819         /*
820          *      Associate the clients structure with the section, where
821          *      it will be freed once the section is freed.
822          */
823         if (cf_data_add(section, "clients", clients, (void *) clients_free) < 0) {
824                 cf_log_err(cf_sectiontoitem(section),
825                            "Failed to associate clients with section %s",
826                        cf_section_name1(section));
827                 clients_free(clients);
828                 return NULL;
829         }
830
831         for (cs = cf_subsection_find_next(section, NULL, "client");
832              cs != NULL;
833              cs = cf_subsection_find_next(section, cs, "client")) {
834                 c = client_parse(cs, in_server);
835                 if (!c) {
836                         return NULL;
837                 }
838
839                 /*
840                  *      FIXME: Add the client as data via cf_data_add,
841                  *      for migration issues.
842                  */
843
844 #ifdef WITH_DYNAMIC_CLIENTS
845 #ifdef HAVE_DIRENT_H
846                 if (c->client_server) {
847                         const char *value;
848                         CONF_PAIR *cp;
849                         DIR             *dir;
850                         struct dirent   *dp;
851                         struct stat stat_buf;
852                         char buf2[2048];
853
854                         /*
855                          *      Find the directory where individual
856                          *      client definitions are stored.
857                          */
858                         cp = cf_pair_find(cs, "directory");
859                         if (!cp) goto add_client;
860                         
861                         value = cf_pair_value(cp);
862                         if (!value) {
863                                 cf_log_err(cf_sectiontoitem(cs),
864                                            "The \"directory\" entry must not be empty");
865                                 client_free(c);
866                                 return NULL;
867                         }
868
869                         DEBUG("including dynamic clients in %s", value);
870                         
871                         dir = opendir(value);
872                         if (!dir) {
873                                 cf_log_err(cf_sectiontoitem(cs), "Error reading directory %s: %s", value, strerror(errno));
874                                 client_free(c);
875                                 return NULL;
876                         }
877                         
878                         /*
879                          *      Read the directory, ignoring "." files.
880                          */
881                         while ((dp = readdir(dir)) != NULL) {
882                                 const char *p;
883                                 RADCLIENT *dc;
884
885                                 if (dp->d_name[0] == '.') continue;
886
887                                 /*
888                                  *      Check for valid characters
889                                  */
890                                 for (p = dp->d_name; *p != '\0'; p++) {
891                                         if (isalpha((int)*p) ||
892                                             isdigit((int)*p) ||
893                                             (*p == ':') ||
894                                             (*p == '.')) continue;
895                                                 break;
896                                 }
897                                 if (*p != '\0') continue;
898
899                                 snprintf(buf2, sizeof(buf2), "%s/%s",
900                                          value, dp->d_name);
901
902                                 if ((stat(buf2, &stat_buf) != 0) ||
903                                     S_ISDIR(stat_buf.st_mode)) continue;
904
905                                 dc = client_read(buf2, in_server, TRUE);
906                                 if (!dc) {
907                                         cf_log_err(cf_sectiontoitem(cs),
908                                                    "Failed reading client file \"%s\"", buf2);
909                                         client_free(c);
910                                         return NULL;
911                                 }
912
913                                 /*
914                                  *      Validate, and add to the list.
915                                  */
916                                 if (!client_validate(clients, c, dc)) {
917                                         
918                                         client_free(c);
919                                         return NULL;
920                                 }
921                         } /* loop over the directory */
922                 }
923 #endif /* HAVE_DIRENT_H */
924 #endif /* WITH_DYNAMIC_CLIENTS */
925
926         add_client:
927                 if (!client_add(clients, c)) {
928                         cf_log_err(cf_sectiontoitem(cs),
929                                    "Failed to add client %s",
930                                    cf_section_name2(cs));
931                         client_free(c);
932                         return NULL;
933                 }
934
935         }
936
937         /*
938          *      Replace the global list of clients with the new one.
939          *      The old one is still referenced from the original
940          *      configuration, and will be freed when that is freed.
941          */
942         if (global) {
943                 root_clients = clients;
944         }
945
946         return clients;
947 }
948
949 #ifdef WITH_DYNAMIC_CLIENTS
950 /*
951  *      We overload this structure a lot.
952  */
953 static const CONF_PARSER dynamic_config[] = {
954         { "FreeRADIUS-Client-IP-Address",  PW_TYPE_IPADDR,
955           offsetof(RADCLIENT, ipaddr), 0, NULL },
956         { "FreeRADIUS-Client-IPv6-Address",  PW_TYPE_IPV6ADDR,
957           offsetof(RADCLIENT, ipaddr), 0, NULL },
958
959         { "FreeRADIUS-Client-Require-MA",  PW_TYPE_BOOLEAN,
960           offsetof(RADCLIENT, message_authenticator), NULL, NULL },
961
962         { "FreeRADIUS-Client-Secret",  PW_TYPE_STRING_PTR,
963           offsetof(RADCLIENT, secret), 0, "" },
964         { "FreeRADIUS-Client-Shortname",  PW_TYPE_STRING_PTR,
965           offsetof(RADCLIENT, shortname), 0, "" },
966         { "FreeRADIUS-Client-NAS-Type",  PW_TYPE_STRING_PTR,
967           offsetof(RADCLIENT, nastype), 0, NULL },
968         { "FreeRADIUS-Client-Virtual-Server",  PW_TYPE_STRING_PTR,
969           offsetof(RADCLIENT, server), 0, NULL },
970
971         { NULL, -1, 0, NULL, NULL }
972 };
973
974
975 int client_validate(RADCLIENT_LIST *clients, RADCLIENT *master, RADCLIENT *c)
976 {
977         char buffer[128];
978
979         /*
980          *      No virtual server defined.  Inherit the parent's
981          *      definition.
982          */
983         if (master->server && !c->server) {
984                 c->server = strdup(master->server);
985         }
986
987         /*
988          *      If the client network isn't global (not tied to a
989          *      virtual server), then ensure that this clients server
990          *      is the same as the enclosing networks virtual server.
991          */
992         if (master->server &&
993              (strcmp(master->server, c->server) != 0)) {
994                 DEBUG("- Cannot add client %s: Virtual server %s is not the same as the virtual server for the network.",
995                       ip_ntoh(&c->ipaddr,
996                               buffer, sizeof(buffer)),
997                       c->server);
998
999                 goto error;
1000         }
1001
1002         if (!client_add(clients, c)) {
1003                 DEBUG("- Cannot add client %s: Internal error",
1004                       ip_ntoh(&c->ipaddr,
1005                               buffer, sizeof(buffer)));
1006
1007                 goto error;
1008         }
1009
1010         /*
1011          *      Initialize the remaining fields.
1012          */
1013         c->dynamic = TRUE;
1014         c->lifetime = master->lifetime;
1015         c->created = time(NULL);
1016         c->longname = strdup(c->shortname);
1017
1018         DEBUG("- Added client %s with shared secret %s",
1019               ip_ntoh(&c->ipaddr, buffer, sizeof(buffer)),
1020               c->secret);
1021
1022         return 1;
1023
1024  error:
1025         client_free(c);
1026         return 0;
1027 }
1028
1029
1030 RADCLIENT *client_create(RADCLIENT_LIST *clients, REQUEST *request)
1031 {
1032         int i, *pi;
1033         char **p;
1034         RADCLIENT *c;
1035         char buffer[128];
1036
1037         if (!clients || !request) return NULL;
1038
1039         c = rad_malloc(sizeof(*c));
1040         memset(c, 0, sizeof(*c));
1041         c->cs = request->client->cs;
1042         c->ipaddr.af = AF_UNSPEC;
1043
1044         for (i = 0; dynamic_config[i].name != NULL; i++) {
1045                 DICT_ATTR *da;
1046                 VALUE_PAIR *vp;
1047
1048                 da = dict_attrbyname(dynamic_config[i].name);
1049                 if (!da) {
1050                         DEBUG("- Cannot add client %s: attribute \"%s\"is not in the dictionary",
1051                               ip_ntoh(&request->packet->src_ipaddr,
1052                                       buffer, sizeof(buffer)),
1053                               dynamic_config[i].name);
1054                 error:
1055                         client_free(c);
1056                         return NULL;
1057                 }
1058
1059                 vp = pairfind(request->config_items, da->attr);
1060                 if (!vp) {
1061                         /*
1062                          *      Not required.  Skip it.
1063                          */
1064                         if (!dynamic_config[i].dflt) continue;
1065                         
1066                         DEBUG("- Cannot add client %s: Required attribute \"%s\" is missing.",  
1067                               ip_ntoh(&request->packet->src_ipaddr,
1068                                       buffer, sizeof(buffer)),
1069                               dynamic_config[i].name);
1070                         goto error;
1071                 }
1072
1073                 switch (dynamic_config[i].type) {
1074                 case PW_TYPE_IPADDR:
1075                         c->ipaddr.af = AF_INET;
1076                         c->ipaddr.ipaddr.ip4addr.s_addr = vp->vp_ipaddr;
1077                         c->prefix = 32;
1078                         break;
1079
1080                 case PW_TYPE_IPV6ADDR:
1081                         c->ipaddr.af = AF_INET6;
1082                         c->ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
1083                         c->prefix = 128;
1084                         break;
1085
1086                 case PW_TYPE_STRING_PTR:
1087                         p = (char **) ((char *) c + dynamic_config[i].offset);
1088                         if (*p) free(*p);
1089                         *p = strdup(vp->vp_strvalue);
1090                         break;
1091
1092                 case PW_TYPE_BOOLEAN:
1093                         pi = (int *) ((char *) c + dynamic_config[i].offset);
1094                         *pi = vp->vp_integer;
1095                         break;
1096
1097                 default:
1098                         goto error;
1099                 }
1100         }
1101
1102         if (c->ipaddr.af == AF_UNSPEC) {
1103                 DEBUG("- Cannot add client %s: No IP address was specified.",
1104                       ip_ntoh(&request->packet->src_ipaddr,
1105                               buffer, sizeof(buffer)));
1106
1107                 goto error;
1108         }
1109
1110         if (fr_ipaddr_cmp(&request->packet->src_ipaddr, &c->ipaddr) != 0) {
1111                 char buf2[128];
1112
1113                 DEBUG("- Cannot add client %s: IP address %s do not match",
1114                       ip_ntoh(&request->packet->src_ipaddr,
1115                               buffer, sizeof(buffer)),
1116                       ip_ntoh(&c->ipaddr,
1117                               buf2, sizeof(buf2)));                   
1118                 goto error;
1119         }
1120
1121         if (!client_validate(clients, request->client, c)) {
1122                 return NULL;
1123         }
1124
1125         return c;
1126 }
1127
1128 /*
1129  *      Read a client definition from the given filename.
1130  */
1131 RADCLIENT *client_read(const char *filename, int in_server, int flag)
1132 {
1133         const char *p;
1134         RADCLIENT *c;
1135         CONF_SECTION *cs;
1136         char buffer[256];
1137
1138         if (!filename) return NULL;
1139
1140         cs = cf_file_read(filename);
1141         if (!cs) return NULL;
1142
1143         c = client_parse(cf_section_sub_find(cs, "client"), in_server);
1144
1145         p = strrchr(filename, FR_DIR_SEP);
1146         if (p) {
1147                 p++;
1148         } else {
1149                 p = filename;
1150         }
1151
1152         if (!flag) return c;
1153
1154         /*
1155          *      Additional validations
1156          */
1157         ip_ntoh(&c->ipaddr, buffer, sizeof(buffer));
1158         if (strcmp(p, buffer) != 0) {
1159                 DEBUG("Invalid client definition in %s: IP address %s does not match name %s", filename, buffer, p);
1160                 client_free(c);
1161                 return NULL;
1162         }
1163
1164
1165
1166         return c;
1167 }
1168 #endif