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