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