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