Moved code that turns a conf-reference into a CONF_ITEM into
[freeradius.git] / src / main / conffile.c
1 /*
2  * conffile.c   Read the radiusd.conf file.
3  *
4  *              Yep I should learn to use lex & yacc, or at least
5  *              write a decent parser. I know how to do that, really :)
6  *              miquels@cistron.nl
7  *
8  * Version:     $Id$
9  *
10  *   This program is free software; you can redistribute it and/or modify
11  *   it under the terms of the GNU General Public License as published by
12  *   the Free Software Foundation; either version 2 of the License, or
13  *   (at your option) any later version.
14  *
15  *   This program is distributed in the hope that it will be useful,
16  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *   GNU General Public License for more details.
19  *
20  *   You should have received a copy of the GNU General Public License
21  *   along with this program; if not, write to the Free Software
22  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  *
24  * Copyright 2000,2006  The FreeRADIUS server project
25  * Copyright 2000  Miquel van Smoorenburg <miquels@cistron.nl>
26  * Copyright 2000  Alan DeKok <aland@ox.org>
27  */
28
29 #include <freeradius-devel/ident.h>
30 RCSID("$Id$")
31
32 #include <freeradius-devel/radiusd.h>
33 #include <freeradius-devel/rad_assert.h>
34
35 #ifdef HAVE_DIRENT_H
36 #include <dirent.h>
37
38 #ifdef HAVE_SYS_STAT_H
39 #include <sys/stat.h>
40 #endif
41 #endif
42
43 #include <ctype.h>
44
45 typedef enum conf_type {
46         CONF_ITEM_INVALID = 0,
47         CONF_ITEM_PAIR,
48         CONF_ITEM_SECTION,
49         CONF_ITEM_DATA
50 } CONF_ITEM_TYPE;
51
52 struct conf_item {
53         struct conf_item *next;
54         struct conf_part *parent;
55         int lineno;
56         const char *filename;
57         CONF_ITEM_TYPE type;
58 };
59 struct conf_pair {
60         CONF_ITEM item;
61         char *attr;
62         char *value;
63         LRAD_TOKEN operator;
64         LRAD_TOKEN value_type;
65 };
66 struct conf_part {
67         CONF_ITEM item;
68         const char *name1;
69         const char *name2;
70         struct conf_item *children;
71         struct conf_item *tail; /* for speed */
72         CONF_SECTION    *template;
73         rbtree_t        *pair_tree; /* and a partridge.. */
74         rbtree_t        *section_tree; /* no jokes here */
75         rbtree_t        *name2_tree; /* for sections of the same name2 */
76         rbtree_t        *data_tree;
77         void            *base;
78         int depth;
79         const CONF_PARSER *variables;
80 };
81
82
83 /*
84  *      Internal data that is associated with a configuration section,
85  *      so that we don't have to track it separately.
86  */
87 struct conf_data {
88         CONF_ITEM  item;
89         const char *name;
90         int        flag;
91         void       *data;       /* user data */
92         void       (*free)(void *); /* free user data function */
93 };
94
95
96 static int cf_data_add_internal(CONF_SECTION *cs, const char *name,
97                                 void *data, void (*data_free)(void *),
98                                 int flag);
99 static void *cf_data_find_internal(CONF_SECTION *cs, const char *name,
100                                    int flag);
101
102 /*
103  *      Isolate the scary casts in these tiny provably-safe functions
104  */
105 CONF_PAIR *cf_itemtopair(CONF_ITEM *ci)
106 {
107         if (ci == NULL)
108                 return NULL;
109         rad_assert(ci->type == CONF_ITEM_PAIR);
110         return (CONF_PAIR *)ci;
111 }
112 CONF_SECTION *cf_itemtosection(CONF_ITEM *ci)
113 {
114         if (ci == NULL)
115                 return NULL;
116         rad_assert(ci->type == CONF_ITEM_SECTION);
117         return (CONF_SECTION *)ci;
118 }
119 CONF_ITEM *cf_pairtoitem(CONF_PAIR *cp)
120 {
121         if (cp == NULL)
122                 return NULL;
123         return (CONF_ITEM *)cp;
124 }
125 CONF_ITEM *cf_sectiontoitem(CONF_SECTION *cs)
126 {
127         if (cs == NULL)
128                 return NULL;
129         return (CONF_ITEM *)cs;
130 }
131
132 static CONF_DATA *cf_itemtodata(CONF_ITEM *ci)
133 {
134         if (ci == NULL)
135                 return NULL;
136         rad_assert(ci->type == CONF_ITEM_DATA);
137         return (CONF_DATA *)ci;
138 }
139 static CONF_ITEM *cf_datatoitem(CONF_DATA *cd)
140 {
141         if (cd == NULL)
142                 return NULL;
143         return (CONF_ITEM *)cd;
144 }
145
146 /*
147  *      Create a new CONF_PAIR
148  */
149 static CONF_PAIR *cf_pair_alloc(const char *attr, const char *value,
150                                 LRAD_TOKEN operator, LRAD_TOKEN value_type,
151                                 CONF_SECTION *parent)
152 {
153         CONF_PAIR *cp;
154
155         cp = rad_malloc(sizeof(*cp));
156         memset(cp, 0, sizeof(*cp));
157         cp->item.type = CONF_ITEM_PAIR;
158         cp->item.parent = parent;
159         cp->attr = strdup(attr);
160         if (value) cp->value = strdup(value);
161         cp->value_type = value_type;
162         cp->operator = operator;
163
164         return cp;
165 }
166
167 /*
168  *      Free a CONF_PAIR
169  */
170 void cf_pair_free(CONF_PAIR **cp)
171 {
172         if (!cp || !*cp) return;
173
174         if ((*cp)->attr)
175                 free((*cp)->attr);
176         if ((*cp)->value)
177                 free((*cp)->value);
178
179 #ifndef NDEBUG
180         memset(*cp, 0, sizeof(*cp));
181 #endif
182         free(*cp);
183
184         *cp = NULL;
185 }
186
187
188 static void cf_data_free(CONF_DATA **cd)
189 {
190         if (!cd || !*cd) return;
191
192         if ((*cd)->flag != 0) free((*cd)->name);
193         if (!(*cd)->free) {
194                 free((*cd)->data);
195         } else {
196                 ((*cd)->free)((*cd)->data);
197         }
198 #ifndef NDEBUG
199         memset(*cd, 0, sizeof(*cd));
200 #endif
201         free(*cd);
202         *cd = NULL;
203 }
204
205 /*
206  *      rbtree callback function
207  */
208 static int pair_cmp(const void *a, const void *b)
209 {
210         const CONF_PAIR *one = a;
211         const CONF_PAIR *two = b;
212
213         return strcmp(one->attr, two->attr);
214 }
215
216
217 /*
218  *      rbtree callback function
219  */
220 static int section_cmp(const void *a, const void *b)
221 {
222         const CONF_SECTION *one = a;
223         const CONF_SECTION *two = b;
224
225         return strcmp(one->name1, two->name1);
226 }
227
228
229 /*
230  *      rbtree callback function
231  */
232 static int name2_cmp(const void *a, const void *b)
233 {
234         const CONF_SECTION *one = a;
235         const CONF_SECTION *two = b;
236
237         rad_assert(strcmp(one->name1, two->name1) == 0);
238
239         if (!one->name2 && !two->name2) return 0;
240         if (!one->name2) return -1;
241         if (!two->name2) return +1;
242
243         return strcmp(one->name2, two->name2);
244 }
245
246
247 /*
248  *      rbtree callback function
249  */
250 static int data_cmp(const void *a, const void *b)
251 {
252         int rcode;
253
254         const CONF_DATA *one = a;
255         const CONF_DATA *two = b;
256
257         rcode = one->flag - two->flag;
258         if (rcode != 0) return rcode;
259
260         return strcmp(one->name, two->name);
261 }
262
263
264 /*
265  *      Free strings we've parsed into data structures.
266  */
267 static void cf_section_parse_free(void *base, const CONF_PARSER *variables)
268 {
269         int i;
270
271         /*
272          *      Don't automatically free the strings if we're being
273          *      called from a module.  This is also for clients.c,
274          *      where client_free() expects to be able to free the
275          *      client structure.  If we moved everything to key off
276          *      of the config files, we might solve some problems...
277          */
278         if (!variables) return;
279
280         /*
281          *      Free up dynamically allocated string pointers.
282          */
283         for (i = 0; variables[i].name != NULL; i++) {
284                 char **p;
285
286                 if ((variables[i].type != PW_TYPE_STRING_PTR) &&
287                     (variables[i].type != PW_TYPE_FILENAME)) {
288                         continue;
289                 }
290
291                 /*
292                  *      No base struct offset, data must be the pointer.
293                  *      If data doesn't exist, ignore the entry, there
294                  *      must be something wrong.
295                  */
296                 if (!base) {
297                         if (!variables[i].data) {
298                                 continue;
299                         }
300
301                         p = (char **) variables[i].data;;
302
303                 } else if (variables[i].data) {
304                         p = (char **) variables[i].data;;
305
306                 } else {
307                         p = (char **) (((char *)base) + variables[i].offset);
308                 }
309
310                 free(*p);
311                 *p = NULL;
312         }
313 }
314
315
316 /*
317  *      Free a CONF_SECTION
318  */
319 void cf_section_free(CONF_SECTION **cs)
320 {
321         CONF_ITEM       *ci, *next;
322
323         if (!cs || !*cs) return;
324
325         if ((*cs)->variables) {
326                 cf_section_parse_free((*cs)->base, (*cs)->variables);
327         }
328
329         for (ci = (*cs)->children; ci; ci = next) {
330                 next = ci->next;
331
332                 switch (ci->type) {
333                 case CONF_ITEM_PAIR: {
334                                 CONF_PAIR *pair = cf_itemtopair(ci);
335                                 cf_pair_free(&pair);
336                         }
337                         break;
338
339                 case CONF_ITEM_SECTION: {
340                                 CONF_SECTION *section = cf_itemtosection(ci);
341                                 cf_section_free(&section);
342                         }
343                         break;
344
345                 case CONF_ITEM_DATA: {
346                                 CONF_DATA *data = cf_itemtodata(ci);
347                                 cf_data_free(&data);
348                         }
349                         break;
350
351                 default:        /* should really be an error. */
352                         break;
353                 }
354         }
355
356         if ((*cs)->name1)
357                 free((*cs)->name1);
358         if ((*cs)->name2)
359                 free((*cs)->name2);
360         if ((*cs)->pair_tree)
361                 rbtree_free((*cs)->pair_tree);
362         if ((*cs)->section_tree)
363                 rbtree_free((*cs)->section_tree);
364         if ((*cs)->name2_tree)
365                 rbtree_free((*cs)->name2_tree);
366         if ((*cs)->data_tree)
367                 rbtree_free((*cs)->data_tree);
368
369         /*
370          * And free the section
371          */
372 #ifndef NDEBUG
373         memset(*cs, 0, sizeof(*cs));
374 #endif
375         free(*cs);
376
377         *cs = NULL;
378 }
379
380
381 /*
382  *      Allocate a CONF_SECTION
383  */
384 static CONF_SECTION *cf_section_alloc(const char *name1, const char *name2,
385                                       CONF_SECTION *parent)
386 {
387         CONF_SECTION    *cs;
388
389         if (!name1) return NULL;
390
391         cs = rad_malloc(sizeof(*cs));
392         memset(cs, 0, sizeof(*cs));
393         cs->item.type = CONF_ITEM_SECTION;
394         cs->item.parent = parent;
395         cs->name1 = strdup(name1);
396         if (!cs->name1) {
397                 cf_section_free(&cs);
398                 return NULL;
399         }
400
401         if (name2 && *name2) {
402                 cs->name2 = strdup(name2);
403                 if (!cs->name2) {
404                         cf_section_free(&cs);
405                         return NULL;
406                 }
407         }
408         cs->pair_tree = rbtree_create(pair_cmp, NULL, 0);
409         if (!cs->pair_tree) {
410                 cf_section_free(&cs);
411                 return NULL;
412         }
413
414         /*
415          *      Don't create a data tree, it may not be needed.
416          */
417
418         /*
419          *      Don't create the section tree here, it may not
420          *      be needed.
421          */
422
423         if (parent) cs->depth = parent->depth + 1;
424
425         return cs;
426 }
427
428
429 /*
430  *      Add an item to a configuration section.
431  */
432 static void cf_item_add(CONF_SECTION *cs, CONF_ITEM *ci)
433 {
434         if (!cs->children) {
435                 rad_assert(cs->tail == NULL);
436                 cs->children = ci;
437         } else {
438                 rad_assert(cs->tail != NULL);
439                 cs->tail->next = ci;
440         }
441
442         /*
443          *      Update the trees (and tail) for each item added.
444          */
445         for (/* nothing */; ci != NULL; ci = ci->next) {
446                 cs->tail = ci;
447
448                 /*
449                  *      For fast lookups, pair's and sections get
450                  *      added to rbtree's.
451                  */
452                 switch (ci->type) {
453                         case CONF_ITEM_PAIR:
454                                 rbtree_insert(cs->pair_tree, ci);
455                                 break;
456
457                         case CONF_ITEM_SECTION: {
458                                 const CONF_SECTION *cs_new = cf_itemtosection(ci);
459
460                                 if (!cs->section_tree) {
461                                         cs->section_tree = rbtree_create(section_cmp, NULL, 0);
462                                         /* ignore any errors */
463                                 }
464
465                                 if (cs->section_tree) {
466                                         rbtree_insert(cs->section_tree, cs_new);                                }
467
468                                 /*
469                                  *      Two names: find the named instance.
470                                  */
471                                 {
472                                         CONF_SECTION *old_cs;
473
474                                         /*
475                                          *      Find the FIRST
476                                          *      CONF_SECTION having
477                                          *      the given name1, and
478                                          *      create a new tree
479                                          *      under it.
480                                          */
481                                         old_cs = rbtree_finddata(cs->section_tree, cs_new);
482                                         if (!old_cs) return; /* this is a bad error! */
483
484                                         if (!old_cs->name2_tree) {
485                                                 old_cs->name2_tree = rbtree_create(name2_cmp,
486                                                                                    NULL, 0);
487                                         }
488                                         if (old_cs->name2_tree) {
489                                                 rbtree_insert(old_cs->name2_tree, cs_new);
490                                         }
491                                 } /* had a name2 */
492                                 break;
493                         } /* was a section */
494
495                         case CONF_ITEM_DATA:
496                                 if (!cs->data_tree) {
497                                         cs->data_tree = rbtree_create(data_cmp, NULL, 0);
498                                 }
499                                 if (cs->data_tree) {
500                                         rbtree_insert(cs->data_tree, ci);
501                                 }
502                                 break;
503
504                         default: /* FIXME: assert & error! */
505                                 break;
506
507                 } /* switch over conf types */
508         } /* loop over ci */
509 }
510
511
512 static const CONF_ITEM *cf_reference_item(const CONF_SECTION *parentcs,
513                                           const CONF_SECTION *outercs,
514                                           const char *ptr)
515 {
516         CONF_PAIR *cp;
517         const CONF_SECTION *cs = outercs, *next;
518         char name[8192];
519         char *p;
520
521         strlcpy(name, ptr, sizeof(name));
522         p = name;
523
524         /*
525          *      ".foo" means "foo from the current section"
526          */
527         if (*p == '.') {
528                 p++;
529                 
530                 /*
531                  *      ..foo means "foo from the section
532                  *      enclosing this section" (etc.)
533                  */
534                 while (*p == '.') {
535                         if (cs->item.parent)
536                                 cs = cs->item.parent;
537                         p++;
538                 }
539
540                 /*
541                  *      "foo.bar.baz" means "from the root"
542                  */
543         } else if (strchr(p, '.') != NULL) {
544                 cs = parentcs;
545         }
546
547         while (*p) {
548                 char *q = strchr(p, '.');
549
550                 if (!q) break;
551
552                 *q = '\0';
553                 next = cf_section_sub_find(cs, p);
554                 *q = '.';
555
556                 if (!next) break; /* it MAY be a pair in this section! */
557
558                 cs = next;
559                 p = q + 1;
560         }
561
562         if (!*p) return NULL;
563
564  retry:
565         /*
566          *      Find it in the current referenced
567          *      section.
568          */
569         cp = cf_pair_find(cs, p);
570         if (cp) return cf_pairtoitem(cp);
571
572         next = cf_section_sub_find(cs, p);
573         if (next) return cf_sectiontoitem(next);
574         
575         /*
576          *      "foo" is "in the current section, OR in main".
577          */
578         if ((p == name) && (cs != parentcs)) {
579                 cs = parentcs;
580                 goto retry;
581         }
582
583         return NULL;
584 }
585
586 /*
587  *      Expand the variables in an input string.
588  */
589 static const char *cf_expand_variables(const char *cf, int *lineno,
590                                        const CONF_SECTION *outercs,
591                                        char *output, const char *input)
592 {
593         char *p;
594         const char *end, *ptr;
595         const CONF_SECTION *parentcs;
596         char name[8192];
597
598         /*
599          *      Find the master parent conf section.
600          *      We can't use mainconfig.config, because we're in the
601          *      process of re-building it, and it isn't set up yet...
602          */
603         for (parentcs = outercs;
604              parentcs->item.parent != NULL;
605              parentcs = parentcs->item.parent) {
606                 /* do nothing */
607         }
608
609         p = output;
610         ptr = input;
611         while (*ptr) {
612                 /*
613                  *      Ignore anything other than "${"
614                  */
615                 if ((*ptr == '$') && (ptr[1] == '{')) {
616                         CONF_ITEM *ci;
617                         CONF_PAIR *cp;
618
619                         /*
620                          *      FIXME: Add support for ${foo:-bar},
621                          *      like in xlat.c
622                          */
623
624                         /*
625                          *      Look for trailing '}', and log a
626                          *      warning for anything that doesn't match,
627                          *      and exit with a fatal error.
628                          */
629                         end = strchr(ptr, '}');
630                         if (end == NULL) {
631                                 *p = '\0';
632                                 radlog(L_INFO, "%s[%d]: Variable expansion missing }",
633                                        cf, *lineno);
634                                 return NULL;
635                         }
636
637                         ptr += 2;
638
639                         /*
640                          *      Can't really happen because input lines are
641                          *      capped at 8k, which is sizeof(name)
642                          */
643                         if ((end - ptr) >= sizeof(name)) {
644                                 radlog(L_ERR, "%s[%d]: Reference string is too large",
645                                        cf, *lineno);
646                                 return NULL;
647                         }
648
649                         memcpy(name, ptr, end - ptr);
650                         name[end - ptr] = '\0';
651
652                         ci = cf_reference_item(parentcs, outercs, name);
653                         if (!ci || (ci->type != CONF_ITEM_PAIR)) {
654                                 radlog(L_ERR, "%s[%d]: Reference \"%s\" not found",
655                                        cf, *lineno, input);
656                                 return NULL;
657                         }
658
659                         /*
660                          *  Substitute the value of the variable.
661                          */
662                         cp = cf_itemtopair(ci);
663                         strcpy(p, cp->value);
664                         p += strlen(p);
665                         ptr = end + 1;
666
667                 } else if (memcmp(ptr, "$ENV{", 5) == 0) {
668                         char *env;
669
670                         ptr += 5;
671
672                         /*
673                          *      Look for trailing '}', and log a
674                          *      warning for anything that doesn't match,
675                          *      and exit with a fatal error.
676                          */
677                         end = strchr(ptr, '}');
678                         if (end == NULL) {
679                                 *p = '\0';
680                                 radlog(L_INFO, "%s[%d]: Environment variable expansion missing }",
681                                        cf, *lineno);
682                                 return NULL;
683                         }
684
685                         /*
686                          *      Can't really happen because input lines are
687                          *      capped at 8k, which is sizeof(name)
688                          */
689                         if ((end - ptr) >= sizeof(name)) {
690                                 radlog(L_ERR, "%s[%d]: Environment variable name is too large",
691                                        cf, *lineno);
692                                 return NULL;
693                         }
694
695                         memcpy(name, ptr, end - ptr);
696                         name[end - ptr] = '\0';
697
698                         /*
699                          *      Get the environment variable.
700                          *      If none exists, then make it an empty string.
701                          */
702                         env = getenv(name);
703                         if (env == NULL) {
704                                 *name = '\0';
705                                 env = name;
706                         }
707
708                         strcpy(p, env);
709                         p += strlen(p);
710                         ptr = end + 1;
711
712                 } else {
713                         /*
714                          *      Copy it over verbatim.
715                          */
716                         *(p++) = *(ptr++);
717                 }
718         } /* loop over all of the input string. */
719
720         *p = '\0';
721
722         return output;
723 }
724
725
726 /*
727  *      Parses an item (not a CONF_ITEM) into the specified format,
728  *      with a default value.
729  *
730  *      Returns -1 on error, 0 for correctly parsed, and 1 if the
731  *      default value was used.  Note that the default value will be
732  *      used ONLY if the CONF_PAIR is NULL.
733  */
734 int cf_item_parse(CONF_SECTION *cs, const char *name,
735                   int type, void *data, const char *dflt)
736 {
737         int rcode = 0;
738         char **q;
739         const char *value;
740         lrad_ipaddr_t ipaddr;
741         const CONF_PAIR *cp;
742         char ipbuf[128];
743
744         cp = cf_pair_find(cs, name);
745         if (cp) {
746                 value = cp->value;
747
748         } else if (!dflt) {
749                 return 1;       /* nothing to parse, return default value */
750
751         } else {
752                 rcode = 1;
753                 value = dflt;
754         }
755
756         switch (type) {
757         case PW_TYPE_BOOLEAN:
758                 /*
759                  *      Allow yes/no and on/off
760                  */
761                 if ((strcasecmp(value, "yes") == 0) ||
762                     (strcasecmp(value, "on") == 0)) {
763                         *(int *)data = 1;
764                 } else if ((strcasecmp(value, "no") == 0) ||
765                            (strcasecmp(value, "off") == 0)) {
766                         *(int *)data = 0;
767                 } else {
768                         *(int *)data = 0;
769                         radlog(L_ERR, "Bad value \"%s\" for boolean variable %s", value, name);
770                         return -1;
771                 }
772                 DEBUG2("\t%s = %s", name, value);
773                 break;
774
775         case PW_TYPE_INTEGER:
776                 *(int *)data = strtol(value, 0, 0);
777                 DEBUG2("\t%s = %d", name, *(int *)data);
778                 break;
779
780         case PW_TYPE_STRING_PTR:
781                 q = (char **) data;
782                 if (*q != NULL) {
783                         free(*q);
784                 }
785
786                 /*
787                  *      Expand variables which haven't already been
788                  *      expanded automagically when the configuration
789                  *      file was read.
790                  */
791                 if (value == dflt) {
792                         char buffer[8192];
793
794                         int lineno = cs->item.lineno;
795
796                         /*
797                          *      FIXME: sizeof(buffer)?
798                          */
799                         value = cf_expand_variables("?",
800                                                     &lineno,
801                                                     cs, buffer, value);
802                         if (!value) return -1;
803                 }
804
805                 DEBUG2("\t%s = \"%s\"", name, value ? value : "(null)");
806                 *q = value ? strdup(value) : NULL;
807                 break;
808
809                 /*
810                  *      This is the same as PW_TYPE_STRING_PTR,
811                  *      except that we also "stat" the file, and
812                  *      cache the result.
813                  */
814         case PW_TYPE_FILENAME:
815                 q = (char **) data;
816                 if (*q != NULL) {
817                         free(*q);
818                 }
819
820                 /*
821                  *      Expand variables which haven't already been
822                  *      expanded automagically when the configuration
823                  *      file was read.
824                  */
825                 if (value == dflt) {
826                         char buffer[8192];
827
828                         int lineno = cs->item.lineno;
829
830                         /*
831                          *      FIXME: sizeof(buffer)?
832                          */
833                         value = cf_expand_variables("?",
834                                                     &lineno,
835                                                     cs, buffer, value);
836                         if (!value) return -1;
837                 }
838
839                 DEBUG2("\t%s = \"%s\"", name, value ? value : "(null)");
840                 *q = value ? strdup(value) : NULL;
841
842                 /*
843                  *      And now we "stat" the file.
844                  */
845                 if (*q) {
846                         struct stat buf;
847
848                         if (stat(*q, &buf) == 0) {
849                                 time_t *mtime;
850
851                                 mtime = rad_malloc(sizeof(*mtime));
852                                 *mtime = buf.st_mtime;
853                                 /* FIXME: error? */
854                                 cf_data_add_internal(cs, *q, mtime, free,
855                                                      PW_TYPE_FILENAME);
856                         }
857                 }
858                 break;
859
860         case PW_TYPE_IPADDR:
861                 /*
862                  *      Allow '*' as any address
863                  */
864                 if (strcmp(value, "*") == 0) {
865                         *(uint32_t *) data = htonl(INADDR_ANY);
866                         DEBUG2("\t%s = *", name);
867                         break;
868                 }
869                 if (ip_hton(value, AF_INET, &ipaddr) < 0) {
870                         radlog(L_ERR, "Can't find IP address for host %s", value);
871                         return -1;
872                 }
873                 DEBUG2("\t%s = %s IP address [%s]", name, value,
874                                ip_ntoh(&ipaddr, ipbuf, sizeof(ipbuf)));
875                 *(uint32_t *) data = ipaddr.ipaddr.ip4addr.s_addr;
876                 break;
877
878         case PW_TYPE_IPV6ADDR:
879                 if (ip_hton(value, AF_INET6, &ipaddr) < 0) {
880                         radlog(L_ERR, "Can't find IPv6 address for host %s", value);
881                         return -1;
882                 }
883                 DEBUG2("\t%s = %s IPv6 address [%s]", name, value,
884                                ip_ntoh(&ipaddr, ipbuf, sizeof(ipbuf)));
885                 memcpy(data, &ipaddr.ipaddr.ip6addr,
886                        sizeof(ipaddr.ipaddr.ip6addr));
887                 break;
888
889         default:
890                 radlog(L_ERR, "type %d not supported yet", type);
891                 return -1;
892                 break;
893         } /* switch over variable type */
894
895         return rcode;
896 }
897
898 static const char *parse_spaces = "                                                                                                                                                                                                                                                                ";
899
900 /*
901  *      Parse a configuration section into user-supplied variables.
902  */
903 int cf_section_parse(CONF_SECTION *cs, void *base,
904                      const CONF_PARSER *variables)
905 {
906         int i;
907         void *data;
908
909         if (!cs->name2) {
910                 DEBUG2("%.*s%s {", cs->depth, parse_spaces,
911                        cs->name1);
912         } else {
913                 DEBUG2("%.*s%s %s {", cs->depth, parse_spaces,
914                        cs->name1, cs->name2);
915         }
916
917         /*
918          *      Handle the known configuration parameters.
919          */
920         for (i = 0; variables[i].name != NULL; i++) {
921                 /*
922                  *      Handle subsections specially
923                  */
924                 if (variables[i].type == PW_TYPE_SUBSECTION) {
925                         const CONF_SECTION *subcs;
926                         subcs = cf_section_sub_find(cs, variables[i].name);
927
928                         /*
929                          *      If the configuration section is NOT there,
930                          *      then ignore it.
931                          *
932                          *      FIXME! This is probably wrong... we should
933                          *      probably set the items to their default values.
934                          */
935                         if (!subcs) continue;
936
937                         if (!variables[i].dflt) {
938                                 DEBUG2("Internal sanity check 1 failed in cf_section_parse");
939                                 goto error;
940                         }
941
942                         if (cf_section_parse(subcs, base,
943                                              (const CONF_PARSER *) variables[i].dflt) < 0) {
944                                 goto error;
945                         }
946                         continue;
947                 } /* else it's a CONF_PAIR */
948
949                 if (variables[i].data) {
950                         data = variables[i].data; /* prefer this. */
951                 } else if (base) {
952                         data = ((char *)base) + variables[i].offset;
953                 } else {
954                         DEBUG2("Internal sanity check 2 failed in cf_section_parse");
955                         goto error;
956                 }
957
958                 /*
959                  *      Parse the pair we found, or a default value.
960                  */
961                 if (cf_item_parse(cs, variables[i].name, variables[i].type,
962                                   data, variables[i].dflt) < 0) {
963                         goto error;
964                 }
965         } /* for all variables in the configuration section */
966
967         DEBUG2("%.*s}", cs->depth, parse_spaces);
968
969         cs->base = base;
970         cs->variables = variables;
971
972         return 0;
973
974  error:
975         DEBUG2("%.*s}", cs->depth, parse_spaces);
976         cf_section_parse_free(base, variables);
977         return -1;
978 }
979
980
981 /*
982  *      Sanity check the "if" or "elsif", presuming that the first '('
983  *      has already been eaten.
984  *
985  *      We're not really parsing it here, just checking if it's mostly
986  *      well-formed.
987  */
988 static int condition_looks_ok(const char **ptr)
989 {
990         int num_braces = 1;
991         int quote = 0;
992         const char *p = *ptr;
993
994         while (*p) {
995                 if (quote) {
996                         if (*p == quote) {
997                                 p++;
998                                 quote = 0;
999                                 continue;
1000                         }
1001
1002                         if (*p == '\\') {
1003                                 if (!p[1]) {
1004                                         return 0; /* no trailing slash */
1005                                 }
1006                                 p += 2;
1007                                 continue;
1008                         }
1009                         p++;
1010                         continue;
1011                 }
1012
1013                 switch (*p) {
1014                 case '\\':
1015                         if (!p[1]) {
1016                                 return 0; /* no trailing slash */
1017                         }
1018                         p += 2;
1019                         continue;
1020
1021                 case '(':
1022                         num_braces++;
1023                         p++;
1024                         continue;
1025
1026                 case ')':
1027                         if (num_braces == 1) {
1028                                 const char *q = p + 1;
1029
1030                                 /*
1031                                  *      Validate that there isn't much
1032                                  *      else after the closing brace.
1033                                  */
1034                                 while ((*q == ' ') || (*q == '\t')) q++;
1035
1036                                 /*
1037                                  *      Parse error.
1038                                  */
1039                                 if (*q != '{') {
1040                                         return 0;
1041                                 }
1042
1043                                 *ptr = p + 1; /* include the trailing ')' */
1044                                 return 1;
1045                         }
1046                         num_braces--;
1047                         p++;
1048                         continue;
1049
1050                 case '"':
1051                 case '\'':
1052                 case '/':
1053                 case '`':
1054                         quote = *p;
1055                         /* FALL-THROUGH */
1056
1057                 default:
1058                         p++;
1059                         break;
1060                 }
1061         }
1062
1063         return 0;
1064 }
1065
1066
1067 /*
1068  *      Read a part of the config file.
1069  */
1070 static int cf_section_read(const char *filename, int *lineno, FILE *fp,
1071                            CONF_SECTION *current)
1072
1073 {
1074         CONF_SECTION *this, *css;
1075         CONF_PAIR *cpn;
1076         char *ptr;
1077         const char *value;
1078         char buf[8192];
1079         char buf1[8192];
1080         char buf2[8192];
1081         char buf3[8192];
1082         int t1, t2, t3;
1083         char *cbuf = buf;
1084         int len;
1085
1086         this = current;         /* add items here */
1087
1088         /*
1089          *      Read, checking for line continuations ('\\' at EOL)
1090          */
1091         for (;;) {
1092                 int eof;
1093
1094                 /*
1095                  *      Get data, and remember if we are at EOF.
1096                  */
1097                 eof = (fgets(cbuf, sizeof(buf) - (cbuf - buf), fp) == NULL);
1098                 (*lineno)++;
1099
1100                 len = strlen(cbuf);
1101
1102                 /*
1103                  *      We've filled the buffer, and there isn't
1104                  *      a CR in it.  Die!
1105                  */
1106                 if ((cbuf[len - 1] != '\n') && !feof(fp)) {
1107                         radlog(L_ERR, "%s[%d]: Line too long",
1108                                filename, *lineno);
1109                         return -1;
1110                 }
1111
1112                 /*
1113                  *  Check for continuations.
1114                  */
1115                 if (cbuf[len - 1] == '\n') len--;
1116
1117                 /*
1118                  *      Last character is '\\'.  Over-write it,
1119                  *      and read another line.
1120                  */
1121                 if ((len > 0) && (cbuf[len - 1] == '\\')) {
1122                         if (len >= (sizeof(buf) - 5)) {
1123                                 radlog(L_ERR, "%s[%d]: Line too long",
1124                                        filename, *lineno);
1125                                 return -1;
1126                         }
1127
1128                         cbuf[len - 1] = '\0';
1129                         cbuf += len - 1;
1130                         continue;
1131                 }
1132
1133                 /*
1134                  *  We're at EOF, and haven't read anything.  Stop.
1135                  */
1136                 if (eof && (cbuf == buf)) {
1137                         break;
1138                 }
1139
1140                 ptr = cbuf = buf;
1141                 t1 = gettoken(&ptr, buf1, sizeof(buf1));
1142
1143                 if ((*buf1 == '#') || (*buf1 == '\0')) {
1144                         continue;
1145                 }
1146
1147                 /*
1148                  *      The caller eats "name1 name2 {", and calls us
1149                  *      for the data inside of the section.  So if we
1150                  *      receive a closing brace, then it must mean the
1151                  *      end of the section.
1152                  */
1153                if (t1 == T_RCBRACE) {
1154                        if (this == current) {
1155                                radlog(L_ERR, "%s[%d]: Too many closing braces",
1156                                       filename, *lineno);
1157                                return -1;
1158
1159                        }
1160                        this = this->item.parent;
1161                        continue;
1162                 }
1163
1164                 /*
1165                  *      Allow for $INCLUDE files
1166                  *
1167                  *      This *SHOULD* work for any level include.
1168                  *      I really really really hate this file.  -cparker
1169                  */
1170                if ((strcasecmp(buf1, "$INCLUDE") == 0) ||
1171                    (strcasecmp(buf1, "$-INCLUDE") == 0)) {
1172                         t2 = getword(&ptr, buf2, sizeof(buf2));
1173
1174                         value = cf_expand_variables(filename, lineno, this, buf, buf2);
1175                         if (!value) return -1;
1176
1177 #ifdef HAVE_DIRENT_H
1178                         /*
1179                          *      $INCLUDE foo/
1180                          *
1181                          *      Include ALL non-"dot" files in the directory.
1182                          *      careful!
1183                          */
1184                         if (value[strlen(value) - 1] == '/') {
1185                                 DIR             *dir;
1186                                 struct dirent   *dp;
1187                                 struct stat stat_buf;
1188
1189                                 DEBUG2( "Config:   including files in directory: %s", value );
1190                                 dir = opendir(value);
1191                                 if (!dir) {
1192                                         radlog(L_ERR, "%s[%d]: Error reading directory %s: %s",
1193                                                filename, *lineno, value,
1194                                                strerror(errno));
1195                                         return -1;
1196                                 }
1197
1198                                 /*
1199                                  *      Read the directory, ignoring "." files.
1200                                  */
1201                                 while ((dp = readdir(dir)) != NULL) {
1202                                         const char *p;
1203
1204                                         if (dp->d_name[0] == '.') continue;
1205
1206                                         /*
1207                                          *      Check for valid characters
1208                                          */
1209                                         for (p = dp->d_name; *p != '\0'; p++) {
1210                                                 if (isalpha((int)*p) ||
1211                                                     isdigit((int)*p) ||
1212                                                     (*p == '-') ||
1213                                                     (*p == '_') ||
1214                                                     (*p == '.')) continue;
1215                                                 break;
1216                                         }
1217                                         if (*p != '\0') continue;
1218
1219                                         snprintf(buf2, sizeof(buf2), "%s%s",
1220                                                  value, dp->d_name);
1221                                         if ((stat(buf2, &stat_buf) != 0) ||
1222                                             S_ISDIR(stat_buf.st_mode)) continue;
1223                                         /*
1224                                          *      Read the file into the current
1225                                          *      configuration sectoin.
1226                                          */
1227                                         if (cf_file_include(buf2, this) < 0) {
1228                                                 closedir(dir);
1229                                                 return -1;
1230                                         }
1231                                 }
1232                                 closedir(dir);
1233                         }  else
1234 #endif
1235                         { /* it was a normal file */
1236                                 if (buf1[1] == '-') {
1237                                         struct stat statbuf;
1238
1239                                         if (stat(value, &statbuf) < 0) {
1240                                                 DEBUG("WARNING: Not including file %s: %s", value, strerror(errno));
1241                                                 continue;
1242                                         }
1243                                 }
1244
1245                                 if (cf_file_include(value, this) < 0) {
1246                                         return -1;
1247                                 }
1248                         }
1249                         continue;
1250                 } /* we were in an include */
1251
1252                if (strcasecmp(buf1, "$template") == 0) {
1253                        CONF_ITEM *ci;
1254                        CONF_SECTION *parentcs;
1255                        t2 = getword(&ptr, buf2, sizeof(buf2));
1256
1257                        for (parentcs = current;
1258                             parentcs->item.parent != NULL;
1259                             parentcs = parentcs->item.parent) {
1260                                /* do nothing */
1261                        }
1262
1263                        ci = cf_reference_item(parentcs, this, buf2);
1264                        if (!ci || (ci->type != CONF_ITEM_SECTION)) {
1265                                 radlog(L_ERR, "%s[%d]: Reference \"%s\" not found",
1266                                        filename, *lineno, buf2);
1267                                 return -1;
1268                        }
1269                        
1270                        if (this->template) {
1271                                 radlog(L_ERR, "%s[%d]: Section already has a template",
1272                                        filename, *lineno);
1273                                 return -1;
1274                        }
1275
1276                        this->template = cf_itemtosection(ci);
1277                        continue;
1278                }
1279
1280                 /*
1281                  *      Ensure that the user can't add CONF_PAIRs
1282                  *      with 'internal' names;
1283                  */
1284                 if (buf1[0] == '_') {
1285                         radlog(L_ERR, "%s[%d]: Illegal configuration pair name \"%s\"",
1286                                         filename, *lineno, buf1);
1287                         return -1;
1288                 }
1289
1290                 /*
1291                  *      Grab the next token.
1292                  */
1293                 t2 = gettoken(&ptr, buf2, sizeof(buf2));
1294                 switch (t2) {
1295                 case T_EOL:
1296                 case T_HASH:
1297                         t2 = T_OP_EQ;
1298                         value = NULL;
1299                         goto do_set;
1300
1301                 case T_OP_ADD:
1302                 case T_OP_SUB:
1303                 case T_OP_LE:
1304                 case T_OP_GE:
1305                         if (!this || (strcmp(this->name1, "update") != 0)) {
1306                                 radlog(L_ERR, "%s[%d]: Invalid operator in assignment",
1307                                        filename, *lineno);
1308                                 return -1;
1309                         }
1310
1311                 case T_OP_EQ:
1312                 case T_OP_SET:
1313                 do_set:
1314                         t3 = getstring(&ptr, buf3, sizeof(buf3));
1315
1316                         /*
1317                          *      Handle variable substitution via ${foo}
1318                          */
1319                         if ((t3 == T_BARE_WORD) ||
1320                             (t3 == T_DOUBLE_QUOTED_STRING)) {
1321                                 value = cf_expand_variables(filename, lineno, this,
1322                                                             buf, buf3);
1323                                 if (!value) return -1;
1324                         } else if ((t3 == T_EOL) ||
1325                                    (t3 == T_HASH)) {
1326                                 value = NULL;
1327                         } else {
1328                                 value = buf3;
1329                         }
1330                         
1331                         /*
1332                          *      Add this CONF_PAIR to our CONF_SECTION
1333                          */
1334                         cpn = cf_pair_alloc(buf1, value, t2, t3, this);
1335                         cpn->item.filename = filename;
1336                         cpn->item.lineno = *lineno;
1337                         cf_item_add(this, cf_pairtoitem(cpn));
1338                         continue;
1339
1340                         /*
1341                          *      This horrible code is here to support
1342                          *      if/then/else failover in the
1343                          *      authorize, etc. sections.  It makes no
1344                          *      sense anywhere else.
1345                          */
1346                 case T_LBRACE:
1347                         if ((strcmp(buf1, "if") == 0) ||
1348                             (strcmp(buf1, "elsif") == 0)) {
1349                                 const char *end = ptr;
1350                                 CONF_SECTION *server;
1351
1352                                 if (!condition_looks_ok(&end)) {
1353                                         radlog(L_ERR, "%s[%d]: Parse error in condition at: %s",
1354                                                filename, *lineno, ptr);
1355                                         return -1;
1356                                 }
1357
1358                                 if ((end - ptr) >= (sizeof(buf2) - 1)) {
1359                                         radlog(L_ERR, "%s[%d]: Statement too complicated after \"%s\"",
1360                                                filename, *lineno, buf1);
1361                                         return -1;
1362                                 }
1363
1364                                 /*
1365                                  *      More sanity checking.  This is
1366                                  *      getting to be a horrible hack.
1367                                  */
1368                                 server = this;
1369                                 while (server) {
1370                                         if (strcmp(server->name1, "server") == 0) break;
1371                                         server = server->item.parent;
1372                                 }
1373                                 
1374                                 if (0 && !server) {
1375                                         radlog(L_ERR, "%s[%d]: Processing directives such as \"%s\" cannot be used here.",
1376                                                filename, *lineno, buf1);
1377                                         return -1;
1378                                 }
1379
1380                                 buf2[0] = '(';
1381                                 memcpy(buf2 + 1, ptr, end - ptr);
1382                                 buf2[end - ptr + 1] = '\0';
1383                                 ptr = end + 1;
1384                                 t2 = T_BARE_WORD;
1385                                 goto section_alloc;
1386
1387                         } else {
1388                                 radlog(L_ERR, "%s[%d]: Parse error after \"%s\"",
1389                                        filename, *lineno, buf1);
1390                                 return -1;
1391                         }
1392
1393                         /* FALL-THROUGH */
1394
1395                         /*
1396                          *      No '=', must be a section or sub-section.
1397                          */
1398                 case T_BARE_WORD:
1399                 case T_DOUBLE_QUOTED_STRING:
1400                 case T_SINGLE_QUOTED_STRING:
1401                         t3 = gettoken(&ptr, buf3, sizeof(buf3));
1402                         if (t3 != T_LCBRACE) {
1403                                 radlog(L_ERR, "%s[%d]: Expecting section start brace '{' after \"%s %s\"",
1404                                        filename, *lineno, buf1, buf2);
1405                                 return -1;
1406                         }
1407
1408                 case T_LCBRACE:
1409                 section_alloc:
1410                         css = cf_section_alloc(buf1,
1411                                                t2 == T_LCBRACE ? NULL : buf2,
1412                                                this);
1413                         if (!css) {
1414                                 radlog(L_ERR, "%s[%d]: Failed allocating memory for section",
1415                                                 filename, *lineno);
1416                                 return -1;
1417                         }
1418                         cf_item_add(this, cf_sectiontoitem(css));
1419                         css->item.filename = filename;
1420                         css->item.lineno = *lineno;
1421
1422                         /*
1423                          *      The current section is now the child section.
1424                          */
1425                         this = css;
1426                         continue;
1427
1428                 default:
1429                         radlog(L_ERR, "%s[%d]: Parse error after \"%s\"",
1430                                filename, *lineno, buf1);
1431                         return -1;
1432                 }
1433         }
1434
1435         /*
1436          *      See if EOF was unexpected ..
1437          */
1438         if (feof(fp) && (this != current)) {
1439                 radlog(L_ERR, "%s[%d]: EOF reached without closing brace for section %s starting at line %d",
1440                        filename, *lineno,
1441                        cf_section_name1(this), cf_section_lineno(this));
1442                 return -1;
1443         }
1444
1445         return 0;
1446 }
1447
1448 /*
1449  *      Include one config file in another.
1450  */
1451 int cf_file_include(const char *filename, CONF_SECTION *cs)
1452 {
1453         FILE            *fp;
1454         int             lineno = 0;
1455         struct stat     statbuf;
1456         time_t          *mtime;
1457         CONF_DATA       *cd;
1458
1459         DEBUG2( "Config:   including file: %s", filename);
1460
1461         if (stat(filename, &statbuf) == 0) {
1462 #ifdef S_IWOTH
1463                 if ((statbuf.st_mode & S_IWOTH) != 0) {
1464                         radlog(L_ERR|L_CONS, "Configuration file %s is globally writable.  Refusing to start due to insecure configuration.",
1465                                filename);
1466                         return -1;
1467                 }
1468 #endif
1469
1470 #ifdef S_IROTH
1471                 if (0 && (statbuf.st_mode & S_IROTH) != 0) {
1472                         radlog(L_ERR|L_CONS, "Configuration file %s is globally readable.  Refusing to start due to insecure configuration.",
1473                                filename);
1474                         return -1;
1475                 }
1476 #endif
1477         }
1478
1479         fp = fopen(filename, "r");
1480         if (!fp) {
1481                 radlog(L_ERR|L_CONS, "Unable to open file \"%s\": %s",
1482                        filename, strerror(errno));
1483                 return -1;
1484         }
1485
1486         /*
1487          *      Add the filename to the section
1488          */
1489         mtime = rad_malloc(sizeof(*mtime));
1490         *mtime = statbuf.st_mtime;
1491
1492         if (cf_data_add_internal(cs, filename, mtime, free,
1493                                  PW_TYPE_FILENAME) < 0) {
1494                 radlog(L_ERR|L_CONS, "Internal error open file \"%s\"",
1495                        filename);
1496                 return -1;
1497         }
1498
1499         cd = cf_data_find_internal(cs, filename, PW_TYPE_FILENAME);
1500         if (!cd) {
1501                 radlog(L_ERR|L_CONS, "Internal error open file \"%s\"",
1502                        filename);
1503                 return -1;
1504         }
1505
1506         /*
1507          *      Read the section.  It's OK to have EOF without a
1508          *      matching close brace.
1509          */
1510         if (cf_section_read(cd->name, &lineno, fp, cs) < 0) {
1511                 fclose(fp);
1512                 return -1;
1513         }
1514
1515         fclose(fp);
1516         return 0;
1517 }
1518
1519 /*
1520  *      Bootstrap a config file.
1521  */
1522 CONF_SECTION *cf_file_read(const char *filename)
1523 {
1524         CONF_SECTION *cs;
1525
1526         cs = cf_section_alloc("main", NULL, NULL);
1527         if (!cs) return NULL;
1528
1529         if (cf_file_include(filename, cs) < 0) {
1530                 cf_section_free(&cs);
1531                 return NULL;
1532         }
1533
1534         return cs;
1535 }
1536
1537 /*
1538  * Return a CONF_PAIR within a CONF_SECTION.
1539  */
1540 CONF_PAIR *cf_pair_find(const CONF_SECTION *cs, const char *name)
1541 {
1542         CONF_ITEM       *ci;
1543         CONF_PAIR       *cp = NULL;
1544
1545         if (!cs) cs = mainconfig.config;
1546
1547         /*
1548          *      Find the name in the tree, for speed.
1549          */
1550         if (name) {
1551                 CONF_PAIR mycp;
1552
1553                 mycp.attr = name;
1554                 cp = rbtree_finddata(cs->pair_tree, &mycp);
1555         } else {
1556                 /*
1557                  *      Else find the first one that matches
1558                  */
1559                 for (ci = cs->children; ci; ci = ci->next) {
1560                         if (ci->type == CONF_ITEM_PAIR) {
1561                                 return cf_itemtopair(ci);
1562                         }
1563                 }
1564         }
1565
1566         if (cp || !cs->template) return cp;
1567
1568         return cf_pair_find(cs->template, name);
1569 }
1570
1571 /*
1572  * Return the attr of a CONF_PAIR
1573  */
1574
1575 char *cf_pair_attr(CONF_PAIR *pair)
1576 {
1577         return (pair ? pair->attr : NULL);
1578 }
1579
1580 /*
1581  * Return the value of a CONF_PAIR
1582  */
1583
1584 char *cf_pair_value(CONF_PAIR *pair)
1585 {
1586         return (pair ? pair->value : NULL);
1587 }
1588
1589 /*
1590  *      Copied here for error reporting.
1591  */
1592 extern void librad_log(const char *, ...);
1593
1594 /*
1595  * Turn a CONF_PAIR into a VALUE_PAIR
1596  * For now, ignore the "value_type" field...
1597  */
1598 VALUE_PAIR *cf_pairtovp(CONF_PAIR *pair)
1599 {
1600         DICT_ATTR *da;
1601         VALUE_PAIR *vp;
1602
1603         if (!pair) {
1604                 librad_log("Internal error");
1605                 return NULL;
1606         }
1607
1608         da = dict_attrbyname(pair->attr);
1609         if (!da) {
1610                 librad_log("Unknown attribute %s", pair->attr);
1611                 return NULL;
1612         }
1613
1614         if (!pair->value) {
1615                 librad_log("No value given for attribute %s", pair->attr);
1616                 return NULL;
1617         }
1618
1619         vp = pairalloc(da);
1620         if (!vp) {
1621                 librad_log("Out of memory");
1622                 return NULL;
1623         }
1624
1625         vp->operator = pair->operator;
1626
1627         if ((pair->value_type == T_BARE_WORD) ||
1628             (pair->value_type == T_SINGLE_QUOTED_STRING)) {
1629                 if (!pairparsevalue(vp, pair->value)) {
1630                         pairfree(&vp);
1631                         return NULL;
1632                 }
1633                 vp->flags.do_xlat = 0;
1634         } else {
1635                 vp->flags.do_xlat = 1;
1636         }
1637
1638         return vp;
1639 }
1640
1641 /*
1642  * Return the first label of a CONF_SECTION
1643  */
1644
1645 const char *cf_section_name1(const CONF_SECTION *cs)
1646 {
1647         return (cs ? cs->name1 : NULL);
1648 }
1649
1650 /*
1651  * Return the second label of a CONF_SECTION
1652  */
1653
1654 const char *cf_section_name2(const CONF_SECTION *cs)
1655 {
1656         return (cs ? cs->name2 : NULL);
1657 }
1658
1659 /*
1660  * Find a value in a CONF_SECTION
1661  */
1662 char *cf_section_value_find(const CONF_SECTION *cs, const char *attr)
1663 {
1664         CONF_PAIR       *cp;
1665
1666         cp = cf_pair_find(cs, attr);
1667
1668         return (cp ? cp->value : NULL);
1669 }
1670
1671 /*
1672  * Return the next pair after a CONF_PAIR
1673  * with a certain name (char *attr) If the requested
1674  * attr is NULL, any attr matches.
1675  */
1676
1677 CONF_PAIR *cf_pair_find_next(const CONF_SECTION *cs,
1678                              const CONF_PAIR *pair, const char *attr)
1679 {
1680         CONF_ITEM       *ci;
1681
1682         /*
1683          * If pair is NULL this must be a first time run
1684          * Find the pair with correct name
1685          */
1686
1687         if (pair == NULL){
1688                 return cf_pair_find(cs, attr);
1689         }
1690
1691         ci = cf_pairtoitem(pair)->next;
1692
1693         for (; ci; ci = ci->next) {
1694                 if (ci->type != CONF_ITEM_PAIR)
1695                         continue;
1696                 if (attr == NULL || strcmp(cf_itemtopair(ci)->attr, attr) == 0)
1697                         break;
1698         }
1699
1700         return cf_itemtopair(ci);
1701 }
1702
1703 /*
1704  * Find a CONF_SECTION, or return the root if name is NULL
1705  */
1706
1707 CONF_SECTION *cf_section_find(const char *name)
1708 {
1709         if (name)
1710                 return cf_section_sub_find(mainconfig.config, name);
1711         else
1712                 return mainconfig.config;
1713 }
1714
1715 /*
1716  * Find a sub-section in a section
1717  */
1718
1719 CONF_SECTION *cf_section_sub_find(const CONF_SECTION *cs, const char *name)
1720 {
1721         CONF_ITEM *ci;
1722
1723         /*
1724          *      Do the fast lookup if possible.
1725          */
1726         if (name && cs->section_tree) {
1727                 CONF_SECTION mycs;
1728
1729                 mycs.name1 = name;
1730                 mycs.name2 = NULL;
1731                 return rbtree_finddata(cs->section_tree, &mycs);
1732         }
1733
1734         for (ci = cs->children; ci; ci = ci->next) {
1735                 if (ci->type != CONF_ITEM_SECTION)
1736                         continue;
1737                 if (strcmp(cf_itemtosection(ci)->name1, name) == 0)
1738                         break;
1739         }
1740
1741         return cf_itemtosection(ci);
1742
1743 }
1744
1745
1746 /*
1747  *      Find a CONF_SECTION with both names.
1748  */
1749 CONF_SECTION *cf_section_sub_find_name2(const CONF_SECTION *cs,
1750                                         const char *name1, const char *name2)
1751 {
1752         CONF_ITEM    *ci;
1753
1754         if (!cs) cs = mainconfig.config;
1755
1756         if (name1 && (cs->section_tree)) {
1757                 CONF_SECTION mycs, *master_cs;
1758
1759                 mycs.name1 = name1;
1760                 mycs.name2 = name2;
1761
1762                 master_cs = rbtree_finddata(cs->section_tree, &mycs);
1763                 if (master_cs) {
1764                         return rbtree_finddata(master_cs->name2_tree, &mycs);
1765                 }
1766         }
1767
1768         /*
1769          *      Else do it the old-fashioned way.
1770          */
1771         for (ci = cs->children; ci; ci = ci->next) {
1772                 CONF_SECTION *subcs;
1773
1774                 if (ci->type != CONF_ITEM_SECTION)
1775                         continue;
1776
1777                 subcs = cf_itemtosection(ci);
1778                 if (!name1) {
1779                         if (!subcs->name2) {
1780                                 if (strcmp(subcs->name1, name2) == 0) break;
1781                         } else {
1782                                 if (strcmp(subcs->name2, name2) == 0) break;
1783                         }
1784                         continue; /* don't do the string comparisons below */
1785                 }
1786
1787                 if ((strcmp(subcs->name1, name1) == 0) &&
1788                     (subcs->name2 != NULL) &&
1789                     (strcmp(subcs->name2, name2) == 0))
1790                         break;
1791         }
1792
1793         return cf_itemtosection(ci);
1794 }
1795
1796 /*
1797  * Return the next subsection after a CONF_SECTION
1798  * with a certain name1 (char *name1). If the requested
1799  * name1 is NULL, any name1 matches.
1800  */
1801
1802 CONF_SECTION *cf_subsection_find_next(CONF_SECTION *section,
1803                                       CONF_SECTION *subsection,
1804                                       const char *name1)
1805 {
1806         CONF_ITEM       *ci;
1807
1808         /*
1809          * If subsection is NULL this must be a first time run
1810          * Find the subsection with correct name
1811          */
1812
1813         if (subsection == NULL){
1814                 ci = section->children;
1815         } else {
1816                 ci = cf_sectiontoitem(subsection)->next;
1817         }
1818
1819         for (; ci; ci = ci->next) {
1820                 if (ci->type != CONF_ITEM_SECTION)
1821                         continue;
1822                 if ((name1 == NULL) ||
1823                     (strcmp(cf_itemtosection(ci)->name1, name1) == 0))
1824                         break;
1825         }
1826
1827         return cf_itemtosection(ci);
1828 }
1829
1830
1831 /*
1832  * Return the next section after a CONF_SECTION
1833  * with a certain name1 (char *name1). If the requested
1834  * name1 is NULL, any name1 matches.
1835  */
1836
1837 CONF_SECTION *cf_section_find_next(CONF_SECTION *section,
1838                                    CONF_SECTION *subsection,
1839                                    const char *name1)
1840 {
1841         if (!section->item.parent) return NULL;
1842
1843         return cf_subsection_find_next(section->item.parent, subsection, name1);
1844 }
1845
1846 /*
1847  * Return the next item after a CONF_ITEM.
1848  */
1849
1850 CONF_ITEM *cf_item_find_next(CONF_SECTION *section, CONF_ITEM *item)
1851 {
1852         /*
1853          * If item is NULL this must be a first time run
1854          * Return the first item
1855          */
1856
1857         if (item == NULL) {
1858                 return section->children;
1859         } else {
1860                 return item->next;
1861         }
1862 }
1863
1864 int cf_section_lineno(CONF_SECTION *section)
1865 {
1866         return cf_sectiontoitem(section)->lineno;
1867 }
1868
1869 const char *cf_pair_filename(CONF_PAIR *pair)
1870 {
1871         return cf_pairtoitem(pair)->filename;
1872 }
1873
1874 const char *cf_section_filename(CONF_SECTION *section)
1875 {
1876         return cf_sectiontoitem(section)->filename;
1877 }
1878
1879 int cf_pair_lineno(CONF_PAIR *pair)
1880 {
1881         return cf_pairtoitem(pair)->lineno;
1882 }
1883
1884 int cf_item_is_section(CONF_ITEM *item)
1885 {
1886         return item->type == CONF_ITEM_SECTION;
1887 }
1888 int cf_item_is_pair(CONF_ITEM *item)
1889 {
1890         return item->type == CONF_ITEM_PAIR;
1891 }
1892
1893
1894 static CONF_DATA *cf_data_alloc(CONF_SECTION *parent, const char *name,
1895                                 void *data, void (*data_free)(void *))
1896 {
1897         CONF_DATA *cd;
1898
1899         cd = rad_malloc(sizeof(*cd));
1900         memset(cd, 0, sizeof(*cd));
1901
1902         cd->item.type = CONF_ITEM_DATA;
1903         cd->item.parent = parent;
1904         cd->name = strdup(name);
1905         cd->data = data;
1906         cd->free = data_free;
1907
1908         return cd;
1909 }
1910
1911
1912 static void *cf_data_find_internal(CONF_SECTION *cs, const char *name,
1913                                    int flag)
1914 {
1915         if (!cs || !name) return NULL;
1916
1917         /*
1918          *      Find the name in the tree, for speed.
1919          */
1920         if (cs->data_tree) {
1921                 CONF_DATA mycd;
1922
1923                 mycd.name = name;
1924                 mycd.flag = flag;
1925                 return rbtree_finddata(cs->data_tree, &mycd);
1926         }
1927
1928         return NULL;
1929 }
1930
1931 /*
1932  *      Find data from a particular section.
1933  */
1934 void *cf_data_find(CONF_SECTION *cs, const char *name)
1935 {
1936         CONF_DATA *cd = cf_data_find_internal(cs, name, 0);
1937
1938         if (cd) return cd->data;
1939         return NULL;
1940 }
1941
1942
1943 /*
1944  *      Add named data to a configuration section.
1945  */
1946 static int cf_data_add_internal(CONF_SECTION *cs, const char *name,
1947                                 void *data, void (*data_free)(void *),
1948                                 int flag)
1949 {
1950         CONF_DATA *cd;
1951
1952         if (!cs || !name) return -1;
1953
1954         /*
1955          *      Already exists.  Can't add it.
1956          */
1957         if (cf_data_find_internal(cs, name, flag) != NULL) return -1;
1958
1959         cd = cf_data_alloc(cs, name, data, data_free);
1960         if (!cd) return -1;
1961         cd->flag = flag;
1962
1963         cf_item_add(cs, cf_datatoitem(cd));
1964
1965         return 0;
1966 }
1967
1968 /*
1969  *      Add named data to a configuration section.
1970  */
1971 int cf_data_add(CONF_SECTION *cs, const char *name,
1972                 void *data, void (*data_free)(void *))
1973 {
1974         return cf_data_add_internal(cs, name, data, data_free, 0);
1975 }
1976
1977
1978 /*
1979  *      Copy CONF_DATA from src to dst
1980  */
1981 static void cf_section_copy_data(CONF_SECTION *s, CONF_SECTION *d)
1982 {
1983
1984         CONF_ITEM *cd, *next, **last;
1985
1986         /*
1987          *      Don't check if s->data_tree is NULL.  It's child
1988          *      sections may have data, even if this section doesn't.
1989          */
1990
1991         rad_assert(d->data_tree == NULL);
1992         d->data_tree = s->data_tree;
1993         s->data_tree = NULL;
1994
1995         /*
1996          *      Walk through src, moving CONF_ITEM_DATA
1997          *      to dst, by hand.
1998          */
1999         last = &(s->children);
2000         for (cd = s->children; cd != NULL; cd = next) {
2001                 next = cd->next;
2002
2003                 /*
2004                  *      Recursively copy data from child sections.
2005                  */
2006                 if (cd->type == CONF_ITEM_SECTION) {
2007                         CONF_SECTION *s1, *d1;
2008
2009                         s1 = cf_itemtosection(cd);
2010                         d1 = cf_section_sub_find_name2(d, s1->name1, s1->name2);
2011                         if (d1) {
2012                                 cf_section_copy_data(s1, d1);
2013                         }
2014                         last = &(cd->next);
2015                         continue;
2016                 }
2017
2018                 /*
2019                  *      Not conf data, remember last ptr.
2020                  */
2021                 if (cd->type != CONF_ITEM_DATA) {
2022                         last = &(cd->next);
2023                         continue;
2024                 }
2025
2026                 /*
2027                  *      Remove it from the src list
2028                  */
2029                 *last = cd->next;
2030                 cd->next = NULL;
2031
2032                 /*
2033                  *      Add it to the dst list
2034                  */
2035                 if (!d->children) {
2036                         rad_assert(d->tail == NULL);
2037                         d->children = cd;
2038                 } else {
2039                         rad_assert(d->tail != NULL);
2040                         d->tail->next = cd;
2041                 }
2042                 d->tail = cd;
2043         }
2044 }
2045
2046 /*
2047  *      For a CONF_DATA element, stat the filename, if necessary.
2048  */
2049 static int filename_stat(void *context, void *data)
2050 {
2051         struct stat buf;
2052         CONF_DATA *cd = data;
2053
2054         context = context;      /* -Wunused */
2055
2056         if (cd->flag != PW_TYPE_FILENAME) return 0;
2057
2058         if (stat(cd->name, &buf) < 0) return -1;
2059
2060         if (buf.st_mtime != *(time_t *) cd->data) return -1;
2061
2062         return 0;
2063 }
2064
2065
2066 /*
2067  *      Compare two CONF_SECTIONS.  The items MUST be in the same
2068  *      order.
2069  */
2070 static int cf_section_cmp(CONF_SECTION *a, CONF_SECTION *b)
2071 {
2072         CONF_ITEM *ca = a->children;
2073         CONF_ITEM *cb = b->children;
2074
2075         while (1) {
2076                 CONF_PAIR *pa, *pb;
2077
2078                 /*
2079                  *      Done.  Stop.
2080                  */
2081                 if (!ca && !cb) break;
2082
2083                 /*
2084                  *      Skip CONF_DATA.
2085                  */
2086                 if (ca && ca->type == CONF_ITEM_DATA) {
2087                         ca = ca->next;
2088                         continue;
2089                 }
2090                 if (cb && cb->type == CONF_ITEM_DATA) {
2091                         cb = cb->next;
2092                         continue;
2093                 }
2094
2095                 /*
2096                  *      One is smaller than the other.  Exit.
2097                  */
2098                 if (!ca || !cb) return 0;
2099
2100                 if (ca->type != cb->type) return 0;
2101
2102                 /*
2103                  *      Deal with subsections.
2104                  */
2105                 if (ca->type == CONF_ITEM_SECTION) {
2106                         CONF_SECTION *sa = cf_itemtosection(ca);
2107                         CONF_SECTION *sb = cf_itemtosection(cb);
2108
2109                         if (!cf_section_cmp(sa, sb)) return 0;
2110                         goto next;
2111                 }
2112
2113                 rad_assert(ca->type == CONF_ITEM_PAIR);
2114
2115                 pa = cf_itemtopair(ca);
2116                 pb = cf_itemtopair(cb);
2117
2118                 /*
2119                  *      Different attr and/or value, Exit.
2120                  */
2121                 if ((strcmp(pa->attr, pb->attr) != 0) ||
2122                     (strcmp(pa->value, pb->value) != 0)) return 0;
2123
2124
2125                 /*
2126                  *      And go to the next element.
2127                  */
2128         next:
2129                 ca = ca->next;
2130                 cb = cb->next;
2131         }
2132
2133         /*
2134          *      Walk over the CONF_DATA, stat'ing PW_TYPE_FILENAME.
2135          */
2136         if (a->data_tree &&
2137             (rbtree_walk(a->data_tree, InOrder, filename_stat, NULL) != 0)) {
2138                 return 0;
2139         }
2140
2141         /*
2142          *      They must be the same, say so.
2143          */
2144         return 1;
2145 }
2146
2147
2148 /*
2149  *      Migrate CONF_DATA from one section to another.
2150  */
2151 int cf_section_migrate(CONF_SECTION *dst, CONF_SECTION *src)
2152 {
2153         CONF_ITEM *ci;
2154         CONF_SECTION *s, *d;
2155
2156         for (ci = src->children; ci != NULL; ci = ci->next) {
2157                 if (ci->type != CONF_ITEM_SECTION)
2158                         continue;
2159
2160                 s = cf_itemtosection(ci);
2161                 d = cf_section_sub_find_name2(dst, s->name1, s->name2);
2162
2163                 if (!d) continue; /* not in new one, don't migrate it */
2164
2165                 /*
2166                  *      A section of the same name is in BOTH src & dst,
2167                  *      compare the CONF_PAIR's.  If they're all the same,
2168                  *      then copy the CONF_DATA from one to the other.
2169                  */
2170                 if (cf_section_cmp(s, d)) {
2171                         cf_section_copy_data(s, d);
2172                 }
2173         }
2174
2175         return 1;               /* rcode means anything? */
2176 }
2177
2178 int cf_section_template(CONF_SECTION *cs, CONF_SECTION *template)
2179 {
2180         if (!cs || !template || cs->template || template->template) return -1;
2181
2182         cs->template = template;
2183
2184         return 0;
2185 }
2186
2187
2188 /*
2189  *      This is here to make the rest of the code easier to read.  It
2190  *      ties conffile.c to log.c, but it means we don't have to
2191  *      pollute the 
2192  */
2193 void cf_log_err(CONF_ITEM *ci, const char *fmt, ...)
2194 {
2195         va_list ap;
2196         char buffer[256];
2197
2198         va_start(ap, fmt);
2199         vsnprintf(buffer, sizeof(buffer), fmt, ap);
2200         va_end(ap);
2201
2202         radlog(L_ERR, "%s[%d]: %s", ci->filename, ci->lineno, buffer);
2203 }
2204
2205
2206 #if 0
2207 /*
2208  * JMG dump_config tries to dump the config structure in a readable format
2209  *
2210 */
2211
2212 static int dump_config_section(CONF_SECTION *cs, int indent)
2213 {
2214         CONF_SECTION    *scs;
2215         CONF_PAIR       *cp;
2216         CONF_ITEM       *ci;
2217
2218         /* The DEBUG macro doesn't let me
2219          *   for(i=0;i<indent;++i) debugputchar('\t');
2220          * so I had to get creative. --Pac. */
2221
2222         for (ci = cs->children; ci; ci = ci->next) {
2223                 switch (ci->type) {
2224                 case CONF_ITEM_PAIR:
2225                         cp=cf_itemtopair(ci);
2226                         DEBUG("%.*s%s = %s",
2227                                 indent, "\t\t\t\t\t\t\t\t\t\t\t",
2228                                 cp->attr, cp->value);
2229                         break;
2230
2231                 case CONF_ITEM_SECTION:
2232                         scs=cf_itemtosection(ci);
2233                         DEBUG("%.*s%s %s%s{",
2234                                 indent, "\t\t\t\t\t\t\t\t\t\t\t",
2235                                 scs->name1,
2236                                 scs->name2 ? scs->name2 : "",
2237                                 scs->name2 ?  " " : "");
2238                         dump_config_section(scs, indent+1);
2239                         DEBUG("%.*s}",
2240                                 indent, "\t\t\t\t\t\t\t\t\t\t\t");
2241                         break;
2242
2243                 default:        /* FIXME: Do more! */
2244                         break;
2245                 }
2246         }
2247
2248         return 0;
2249 }
2250
2251 int dump_config(void)
2252 {
2253         return dump_config_section(mainconfig.config, 0);
2254 }
2255 #endif