Do globally writable checks on directories, too
[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         const char *attr;
62         const char *value;
63         FR_TOKEN operator;
64         FR_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 int cf_log_config = 1;
103 int cf_log_modules = 1;
104
105 /*
106  *      Isolate the scary casts in these tiny provably-safe functions
107  */
108 CONF_PAIR *cf_itemtopair(CONF_ITEM *ci)
109 {
110         if (ci == NULL)
111                 return NULL;
112         rad_assert(ci->type == CONF_ITEM_PAIR);
113         return (CONF_PAIR *)ci;
114 }
115 CONF_SECTION *cf_itemtosection(CONF_ITEM *ci)
116 {
117         if (ci == NULL)
118                 return NULL;
119         rad_assert(ci->type == CONF_ITEM_SECTION);
120         return (CONF_SECTION *)ci;
121 }
122 CONF_ITEM *cf_pairtoitem(CONF_PAIR *cp)
123 {
124         if (cp == NULL)
125                 return NULL;
126         return (CONF_ITEM *)cp;
127 }
128 CONF_ITEM *cf_sectiontoitem(CONF_SECTION *cs)
129 {
130         if (cs == NULL)
131                 return NULL;
132         return (CONF_ITEM *)cs;
133 }
134
135 static CONF_DATA *cf_itemtodata(CONF_ITEM *ci)
136 {
137         if (ci == NULL)
138                 return NULL;
139         rad_assert(ci->type == CONF_ITEM_DATA);
140         return (CONF_DATA *)ci;
141 }
142 static CONF_ITEM *cf_datatoitem(CONF_DATA *cd)
143 {
144         if (cd == NULL)
145                 return NULL;
146         return (CONF_ITEM *)cd;
147 }
148
149 /*
150  *      Create a new CONF_PAIR
151  */
152 static CONF_PAIR *cf_pair_alloc(const char *attr, const char *value,
153                                 FR_TOKEN operator, FR_TOKEN value_type,
154                                 CONF_SECTION *parent)
155 {
156         char *p;
157         size_t attr_len, value_len = 0;
158         CONF_PAIR *cp;
159
160         if (!attr) return NULL;
161         attr_len = strlen(attr) + 1;
162         if (value) value_len = strlen(value) + 1;
163
164         p = rad_malloc(sizeof(*cp) + attr_len + value_len);
165
166         cp = (CONF_PAIR *) p;
167         memset(cp, 0, sizeof(*cp));
168         cp->item.type = CONF_ITEM_PAIR;
169         cp->item.parent = parent;
170
171         p += sizeof(*cp);
172         memcpy(p, attr, attr_len);
173         cp->attr = p;
174
175         if (value) {
176                 p += attr_len;
177                 memcpy(p, value, value_len);
178                 cp->value = p;
179         }
180         cp->value_type = value_type;
181         cp->operator = operator;
182
183         return cp;
184 }
185
186 /*
187  *      Free a CONF_PAIR
188  */
189 void cf_pair_free(CONF_PAIR **cp)
190 {
191         if (!cp || !*cp) return;
192
193         /*
194          *      attr && value are allocated contiguous with cp.
195          */
196
197 #ifndef NDEBUG
198         memset(*cp, 0, sizeof(*cp));
199 #endif
200         free(*cp);
201
202         *cp = NULL;
203 }
204
205
206 static void cf_data_free(CONF_DATA **cd)
207 {
208         if (!cd || !*cd) return;
209
210         /* name is allocated contiguous with cd */
211         if (!(*cd)->free) {
212                 free((*cd)->data);
213         } else {
214                 ((*cd)->free)((*cd)->data);
215         }
216 #ifndef NDEBUG
217         memset(*cd, 0, sizeof(*cd));
218 #endif
219         free(*cd);
220         *cd = NULL;
221 }
222
223 /*
224  *      rbtree callback function
225  */
226 static int pair_cmp(const void *a, const void *b)
227 {
228         const CONF_PAIR *one = a;
229         const CONF_PAIR *two = b;
230
231         return strcmp(one->attr, two->attr);
232 }
233
234
235 /*
236  *      rbtree callback function
237  */
238 static int section_cmp(const void *a, const void *b)
239 {
240         const CONF_SECTION *one = a;
241         const CONF_SECTION *two = b;
242
243         return strcmp(one->name1, two->name1);
244 }
245
246
247 /*
248  *      rbtree callback function
249  */
250 static int name2_cmp(const void *a, const void *b)
251 {
252         const CONF_SECTION *one = a;
253         const CONF_SECTION *two = b;
254
255         rad_assert(strcmp(one->name1, two->name1) == 0);
256
257         if (!one->name2 && !two->name2) return 0;
258         if (!one->name2) return -1;
259         if (!two->name2) return +1;
260
261         return strcmp(one->name2, two->name2);
262 }
263
264
265 /*
266  *      rbtree callback function
267  */
268 static int data_cmp(const void *a, const void *b)
269 {
270         int rcode;
271
272         const CONF_DATA *one = a;
273         const CONF_DATA *two = b;
274
275         rcode = one->flag - two->flag;
276         if (rcode != 0) return rcode;
277
278         return strcmp(one->name, two->name);
279 }
280
281
282 /*
283  *      Free strings we've parsed into data structures.
284  */
285 void cf_section_parse_free(CONF_SECTION *cs, void *base)
286 {
287         int i;
288         const CONF_PARSER *variables = cs->variables;
289
290         /*
291          *      Don't automatically free the strings if we're being
292          *      called from a module.  This is also for clients.c,
293          *      where client_free() expects to be able to free the
294          *      client structure.  If we moved everything to key off
295          *      of the config files, we might solve some problems...
296          */
297         if (!variables) return;
298
299         /*
300          *      Free up dynamically allocated string pointers.
301          */
302         for (i = 0; variables[i].name != NULL; i++) {
303                 char **p;
304
305                 if ((variables[i].type != PW_TYPE_STRING_PTR) &&
306                     (variables[i].type != PW_TYPE_FILENAME)) {
307                         continue;
308                 }
309
310                 /*
311                  *      No base struct offset, data must be the pointer.
312                  *      If data doesn't exist, ignore the entry, there
313                  *      must be something wrong.
314                  */
315                 if (!base) {
316                         if (!variables[i].data) {
317                                 continue;
318                         }
319
320                         p = (char **) variables[i].data;;
321
322                 } else if (variables[i].data) {
323                         p = (char **) variables[i].data;;
324
325                 } else {
326                         p = (char **) (((char *)base) + variables[i].offset);
327                 }
328
329                 free(*p);
330                 *p = NULL;
331         }
332 }
333
334
335 /*
336  *      Free a CONF_SECTION
337  */
338 void cf_section_free(CONF_SECTION **cs)
339 {
340         CONF_ITEM       *ci, *next;
341
342         if (!cs || !*cs) return;
343
344         cf_section_parse_free(*cs, (*cs)->base);
345
346         for (ci = (*cs)->children; ci; ci = next) {
347                 next = ci->next;
348
349                 switch (ci->type) {
350                 case CONF_ITEM_PAIR: {
351                                 CONF_PAIR *pair = cf_itemtopair(ci);
352                                 cf_pair_free(&pair);
353                         }
354                         break;
355
356                 case CONF_ITEM_SECTION: {
357                                 CONF_SECTION *section = cf_itemtosection(ci);
358                                 cf_section_free(&section);
359                         }
360                         break;
361
362                 case CONF_ITEM_DATA: {
363                                 CONF_DATA *data = cf_itemtodata(ci);
364                                 cf_data_free(&data);
365                         }
366                         break;
367
368                 default:        /* should really be an error. */
369                         break;
370                 }
371         }
372
373         /*
374          *      Name1 and name2 are allocated contiguous with
375          *      cs.
376          */
377         if ((*cs)->pair_tree)
378                 rbtree_free((*cs)->pair_tree);
379         if ((*cs)->section_tree)
380                 rbtree_free((*cs)->section_tree);
381         if ((*cs)->name2_tree)
382                 rbtree_free((*cs)->name2_tree);
383         if ((*cs)->data_tree)
384                 rbtree_free((*cs)->data_tree);
385
386         /*
387          * And free the section
388          */
389 #ifndef NDEBUG
390         memset(*cs, 0, sizeof(*cs));
391 #endif
392         free(*cs);
393
394         *cs = NULL;
395 }
396
397
398 /*
399  *      Allocate a CONF_SECTION
400  */
401 static CONF_SECTION *cf_section_alloc(const char *name1, const char *name2,
402                                       CONF_SECTION *parent)
403 {
404         size_t name1_len, name2_len = 0;
405         char *p;
406         CONF_SECTION    *cs;
407
408         if (!name1) return NULL;
409
410         name1_len = strlen(name1) + 1;
411         if (name2) name2_len = strlen(name2) + 1;
412
413         p = rad_malloc(sizeof(*cs) + name1_len + name2_len);
414
415         cs = (CONF_SECTION *) p;
416         memset(cs, 0, sizeof(*cs));
417         cs->item.type = CONF_ITEM_SECTION;
418         cs->item.parent = parent;
419
420         p += sizeof(*cs);
421         memcpy(p, name1, name1_len);
422         cs->name1 = p;
423
424         if (name2 && *name2) {
425                 p += name1_len;
426                 memcpy(p, name2, name2_len);
427                 cs->name2 = p;
428         }
429
430         cs->pair_tree = rbtree_create(pair_cmp, NULL, 0);
431         if (!cs->pair_tree) {
432                 cf_section_free(&cs);
433                 return NULL;
434         }
435
436         /*
437          *      Don't create a data tree, it may not be needed.
438          */
439
440         /*
441          *      Don't create the section tree here, it may not
442          *      be needed.
443          */
444
445         if (parent) cs->depth = parent->depth + 1;
446
447         return cs;
448 }
449
450 /*
451  *      Replace pair in a given section with a new pair,
452  *      of the given value.
453  */
454 int cf_pair_replace(CONF_SECTION *cs, CONF_PAIR *cp, const char *value)
455 {
456         CONF_PAIR *newp;
457         CONF_ITEM *ci, *cn, **last;
458
459         newp = cf_pair_alloc(cp->attr, value, cp->operator, cp->value_type,
460                              cs);
461         if (!newp) return -1;
462
463         ci = cf_pairtoitem(cp);
464         cn = cf_pairtoitem(newp);
465
466         /*
467          *      Find the old one from the linked list, and replace it
468          *      with the new one.
469          */
470         for (last = &cs->children; (*last) != NULL; last = &(*last)->next) {
471                 if (*last == ci) {
472                         cn->next = (*last)->next;
473                         *last = cn;
474                         ci->next = NULL;
475                         break;
476                 }
477         }
478
479         rbtree_deletebydata(cs->pair_tree, ci);
480
481         rbtree_insert(cs->pair_tree, cn);
482
483         return 0;
484 }
485
486
487 /*
488  *      Add an item to a configuration section.
489  */
490 static void cf_item_add(CONF_SECTION *cs, CONF_ITEM *ci)
491 {
492         if (!cs || !ci) return;
493
494         if (!cs->children) {
495                 rad_assert(cs->tail == NULL);
496                 cs->children = ci;
497         } else {
498                 rad_assert(cs->tail != NULL);
499                 cs->tail->next = ci;
500         }
501
502         /*
503          *      Update the trees (and tail) for each item added.
504          */
505         for (/* nothing */; ci != NULL; ci = ci->next) {
506                 cs->tail = ci;
507
508                 /*
509                  *      For fast lookups, pair's and sections get
510                  *      added to rbtree's.
511                  */
512                 switch (ci->type) {
513                         case CONF_ITEM_PAIR:
514                                 rbtree_insert(cs->pair_tree, ci);
515                                 break;
516
517                         case CONF_ITEM_SECTION: {
518                                 CONF_SECTION *cs_new = cf_itemtosection(ci);
519
520                                 if (!cs->section_tree) {
521                                         cs->section_tree = rbtree_create(section_cmp, NULL, 0);
522                                         if (!cs->section_tree) {
523                                                 radlog(L_ERR, "Out of memory");
524                                                 _exit(1);
525                                         }
526                                 }
527
528                                 rbtree_insert(cs->section_tree, cs_new);
529
530                                 /*
531                                  *      Two names: find the named instance.
532                                  */
533                                 {
534                                         CONF_SECTION *old_cs;
535
536                                         /*
537                                          *      Find the FIRST
538                                          *      CONF_SECTION having
539                                          *      the given name1, and
540                                          *      create a new tree
541                                          *      under it.
542                                          */
543                                         old_cs = rbtree_finddata(cs->section_tree, cs_new);
544                                         if (!old_cs) return; /* this is a bad error! */
545
546                                         if (!old_cs->name2_tree) {
547                                                 old_cs->name2_tree = rbtree_create(name2_cmp,
548                                                                                    NULL, 0);
549                                         }
550                                         if (old_cs->name2_tree) {
551                                                 rbtree_insert(old_cs->name2_tree, cs_new);
552                                         }
553                                 } /* had a name2 */
554                                 break;
555                         } /* was a section */
556
557                         case CONF_ITEM_DATA:
558                                 if (!cs->data_tree) {
559                                         cs->data_tree = rbtree_create(data_cmp, NULL, 0);
560                                 }
561                                 if (cs->data_tree) {
562                                         rbtree_insert(cs->data_tree, ci);
563                                 }
564                                 break;
565
566                         default: /* FIXME: assert & error! */
567                                 break;
568
569                 } /* switch over conf types */
570         } /* loop over ci */
571 }
572
573
574 CONF_ITEM *cf_reference_item(const CONF_SECTION *parentcs,
575                              CONF_SECTION *outercs,
576                              const char *ptr)
577 {
578         CONF_PAIR *cp;
579         CONF_SECTION *next;
580         const CONF_SECTION *cs = outercs;
581         char name[8192];
582         char *p;
583
584         strlcpy(name, ptr, sizeof(name));
585         p = name;
586
587         /*
588          *      ".foo" means "foo from the current section"
589          */
590         if (*p == '.') {
591                 p++;
592                 
593                 /*
594                  *      ..foo means "foo from the section
595                  *      enclosing this section" (etc.)
596                  */
597                 while (*p == '.') {
598                         if (cs->item.parent)
599                                 cs = cs->item.parent;
600                         p++;
601                 }
602
603                 /*
604                  *      "foo.bar.baz" means "from the root"
605                  */
606         } else if (strchr(p, '.') != NULL) {
607                 if (!parentcs) goto no_such_item;
608
609                 cs = parentcs;
610         }
611
612         while (*p) {
613                 char *q, *r;
614
615                 r = strchr(p, '[');
616                 q = strchr(p, '.');
617                 if (!r && !q) break;
618
619                 if (r && q > r) q = NULL;
620                 if (q && q < r) r = NULL;
621
622                 /*
623                  *      Split off name2.
624                  */
625                 if (r) {
626                         q = strchr(r + 1, ']');
627                         if (!q) return NULL; /* parse error */
628
629                         /*
630                          *      Points to foo[bar]xx: parse error,
631                          *      it should be foo[bar] or foo[bar].baz
632                          */
633                         if (q[1] && q[1] != '.') goto no_such_item;
634
635                         *r = '\0';
636                         *q = '\0';
637                         next = cf_section_sub_find_name2(cs, p, r + 1);
638                         *r = '[';
639                         *q = ']';
640
641                         /*
642                          *      Points to a named instance of a section.
643                          */
644                         if (!q[1]) {
645                                 if (!next) goto no_such_item;
646                                 return cf_sectiontoitem(next);
647                         }
648
649                         q++;    /* ensure we skip the ']' and '.' */
650
651                 } else {
652                         *q = '\0';
653                         next = cf_section_sub_find(cs, p);
654                         *q = '.';
655                 }
656
657                 if (!next) break; /* it MAY be a pair in this section! */
658
659                 cs = next;
660                 p = q + 1;
661         }
662
663         if (!*p) goto no_such_item;
664
665  retry:
666         /*
667          *      Find it in the current referenced
668          *      section.
669          */
670         cp = cf_pair_find(cs, p);
671         if (cp) return cf_pairtoitem(cp);
672
673         next = cf_section_sub_find(cs, p);
674         if (next) return cf_sectiontoitem(next);
675         
676         /*
677          *      "foo" is "in the current section, OR in main".
678          */
679         if ((p == name) && (parentcs != NULL) && (cs != parentcs)) {
680                 cs = parentcs;
681                 goto retry;
682         }
683
684 no_such_item:
685         DEBUG2("WARNING: No such configuration item %s", ptr);
686         return NULL;
687 }
688
689
690 CONF_SECTION *cf_top_section(CONF_SECTION *cs)
691 {
692         if (!cs) return NULL;
693
694         while (cs->item.parent != NULL) {
695                 cs = cs->item.parent;
696         }
697
698         return cs;
699 }
700
701
702 /*
703  *      Expand the variables in an input string.
704  */
705 static const char *cf_expand_variables(const char *cf, int *lineno,
706                                        CONF_SECTION *outercs,
707                                        char *output, size_t outsize,
708                                        const char *input)
709 {
710         char *p;
711         const char *end, *ptr;
712         const CONF_SECTION *parentcs;
713         char name[8192];
714
715         /*
716          *      Find the master parent conf section.
717          *      We can't use mainconfig.config, because we're in the
718          *      process of re-building it, and it isn't set up yet...
719          */
720         parentcs = cf_top_section(outercs);
721
722         p = output;
723         ptr = input;
724         while (*ptr) {
725                 /*
726                  *      Ignore anything other than "${"
727                  */
728                 if ((*ptr == '$') && (ptr[1] == '{')) {
729                         CONF_ITEM *ci;
730                         CONF_PAIR *cp;
731
732                         /*
733                          *      FIXME: Add support for ${foo:-bar},
734                          *      like in xlat.c
735                          */
736
737                         /*
738                          *      Look for trailing '}', and log a
739                          *      warning for anything that doesn't match,
740                          *      and exit with a fatal error.
741                          */
742                         end = strchr(ptr, '}');
743                         if (end == NULL) {
744                                 *p = '\0';
745                                 radlog(L_INFO, "%s[%d]: Variable expansion missing }",
746                                        cf, *lineno);
747                                 return NULL;
748                         }
749
750                         ptr += 2;
751
752                         /*
753                          *      Can't really happen because input lines are
754                          *      capped at 8k, which is sizeof(name)
755                          */
756                         if ((size_t) (end - ptr) >= sizeof(name)) {
757                                 radlog(L_ERR, "%s[%d]: Reference string is too large",
758                                        cf, *lineno);
759                                 return NULL;
760                         }
761
762                         memcpy(name, ptr, end - ptr);
763                         name[end - ptr] = '\0';
764
765                         ci = cf_reference_item(parentcs, outercs, name);
766                         if (!ci || (ci->type != CONF_ITEM_PAIR)) {
767                                 radlog(L_ERR, "%s[%d]: Reference \"%s\" not found",
768                                        cf, *lineno, input);
769                                 return NULL;
770                         }
771
772                         /*
773                          *  Substitute the value of the variable.
774                          */
775                         cp = cf_itemtopair(ci);
776                         if (!cp->value) {
777                                 radlog(L_ERR, "%s[%d]: Reference \"%s\" has no value",
778                                        cf, *lineno, input);
779                                 return NULL;
780                         }
781
782                         if (p + strlen(cp->value) >= output + outsize) {
783                                 radlog(L_ERR, "%s[%d]: Reference \"%s\" is too long",
784                                        cf, *lineno, input);
785                                 return NULL;
786                         }
787
788                         strcpy(p, cp->value);
789                         p += strlen(p);
790                         ptr = end + 1;
791
792                 } else if (memcmp(ptr, "$ENV{", 5) == 0) {
793                         char *env;
794
795                         ptr += 5;
796
797                         /*
798                          *      Look for trailing '}', and log a
799                          *      warning for anything that doesn't match,
800                          *      and exit with a fatal error.
801                          */
802                         end = strchr(ptr, '}');
803                         if (end == NULL) {
804                                 *p = '\0';
805                                 radlog(L_INFO, "%s[%d]: Environment variable expansion missing }",
806                                        cf, *lineno);
807                                 return NULL;
808                         }
809
810                         /*
811                          *      Can't really happen because input lines are
812                          *      capped at 8k, which is sizeof(name)
813                          */
814                         if ((size_t) (end - ptr) >= sizeof(name)) {
815                                 radlog(L_ERR, "%s[%d]: Environment variable name is too large",
816                                        cf, *lineno);
817                                 return NULL;
818                         }
819
820                         memcpy(name, ptr, end - ptr);
821                         name[end - ptr] = '\0';
822
823                         /*
824                          *      Get the environment variable.
825                          *      If none exists, then make it an empty string.
826                          */
827                         env = getenv(name);
828                         if (env == NULL) {
829                                 *name = '\0';
830                                 env = name;
831                         }
832
833                         if (p + strlen(env) >= output + outsize) {
834                                 radlog(L_ERR, "%s[%d]: Reference \"%s\" is too long",
835                                        cf, *lineno, input);
836                                 return NULL;
837                         }
838
839                         strcpy(p, env);
840                         p += strlen(p);
841                         ptr = end + 1;
842
843                 } else {
844                         /*
845                          *      Copy it over verbatim.
846                          */
847                         *(p++) = *(ptr++);
848                 }
849
850                 if (p >= (output + outsize)) {
851                         radlog(L_ERR, "%s[%d]: Reference \"%s\" is too long",
852                                cf, *lineno, input);
853                         return NULL;
854                 }
855         } /* loop over all of the input string. */
856
857         *p = '\0';
858
859         return output;
860 }
861
862
863 /*
864  *      Parses an item (not a CONF_ITEM) into the specified format,
865  *      with a default value.
866  *
867  *      Returns -1 on error, 0 for correctly parsed, and 1 if the
868  *      default value was used.  Note that the default value will be
869  *      used ONLY if the CONF_PAIR is NULL.
870  */
871 int cf_item_parse(CONF_SECTION *cs, const char *name,
872                   int type, void *data, const char *dflt)
873 {
874         int rcode = 0;
875         char **q;
876         const char *value;
877         fr_ipaddr_t ipaddr;
878         const CONF_PAIR *cp = NULL;
879         char ipbuf[128];
880
881         if (cs) cp = cf_pair_find(cs, name);
882         if (cp) {
883                 value = cp->value;
884
885         } else if (!dflt) {
886                 return 1;       /* nothing to parse, return default value */
887
888         } else {
889                 rcode = 1;
890                 value = dflt;
891         }
892
893         if (!value) {
894                 return 0;
895         }
896
897         switch (type) {
898         case PW_TYPE_BOOLEAN:
899                 /*
900                  *      Allow yes/no and on/off
901                  */
902                 if ((strcasecmp(value, "yes") == 0) ||
903                     (strcasecmp(value, "on") == 0)) {
904                         *(int *)data = 1;
905                 } else if ((strcasecmp(value, "no") == 0) ||
906                            (strcasecmp(value, "off") == 0)) {
907                         *(int *)data = 0;
908                 } else {
909                         *(int *)data = 0;
910                         radlog(L_ERR, "Bad value \"%s\" for boolean variable %s", value, name);
911                         return -1;
912                 }
913                 cf_log_info(cs, "\t%s = %s", name, value);
914                 break;
915
916         case PW_TYPE_INTEGER:
917                 *(int *)data = strtol(value, 0, 0);
918                 cf_log_info(cs, "\t%s = %d", name, *(int *)data);
919                 break;
920
921         case PW_TYPE_STRING_PTR:
922                 q = (char **) data;
923                 if (*q != NULL) {
924                         free(*q);
925                 }
926
927                 /*
928                  *      Expand variables which haven't already been
929                  *      expanded automagically when the configuration
930                  *      file was read.
931                  */
932                 if (value == dflt) {
933                         char buffer[8192];
934
935                         int lineno = 0;
936
937                         if (cs) lineno = cs->item.lineno;
938
939                         /*
940                          *      FIXME: sizeof(buffer)?
941                          */
942                         value = cf_expand_variables("<internal>",
943                                                     &lineno,
944                                                     cs, buffer, sizeof(buffer),
945                                                     value);
946                         if (!value) {
947                                 cf_log_err(cf_sectiontoitem(cs),"Failed expanding variable %s", name);
948                                 return -1;
949                         }
950                 }
951
952                 cf_log_info(cs, "\t%s = \"%s\"", name, value ? value : "(null)");
953                 *q = value ? strdup(value) : NULL;
954                 break;
955
956                 /*
957                  *      This is the same as PW_TYPE_STRING_PTR,
958                  *      except that we also "stat" the file, and
959                  *      cache the result.
960                  */
961         case PW_TYPE_FILENAME:
962                 q = (char **) data;
963                 if (*q != NULL) {
964                         free(*q);
965                 }
966
967                 /*
968                  *      Expand variables which haven't already been
969                  *      expanded automagically when the configuration
970                  *      file was read.
971                  */
972                 if (value == dflt) {
973                         char buffer[8192];
974
975                         int lineno = 0;
976
977                         if (cs) lineno = cs->item.lineno;
978
979                         /*
980                          *      FIXME: sizeof(buffer)?
981                          */
982                         value = cf_expand_variables("?",
983                                                     &lineno,
984                                                     cs, buffer, sizeof(buffer),
985                                                     value);
986                         if (!value) return -1;
987                 }
988
989                 cf_log_info(cs, "\t%s = \"%s\"", name, value ? value : "(null)");
990                 *q = value ? strdup(value) : NULL;
991
992                 /*
993                  *      And now we "stat" the file.
994                  *
995                  *      FIXME: This appears to leak memory on exit,
996                  *      and we don't use this information.  So it's
997                  *      commented out for now.
998                  */
999                 if (0 && *q) {
1000                         struct stat buf;
1001
1002                         if (stat(*q, &buf) == 0) {
1003                                 time_t *mtime;
1004
1005                                 mtime = rad_malloc(sizeof(*mtime));
1006                                 *mtime = buf.st_mtime;
1007                                 /* FIXME: error? */
1008                                 cf_data_add_internal(cs, *q, mtime, free,
1009                                                      PW_TYPE_FILENAME);
1010                         }
1011                 }
1012                 break;
1013
1014         case PW_TYPE_IPADDR:
1015                 /*
1016                  *      Allow '*' as any address
1017                  */
1018                 if (strcmp(value, "*") == 0) {
1019                         *(uint32_t *) data = htonl(INADDR_ANY);
1020                         cf_log_info(cs, "\t%s = *", name);
1021                         break;
1022                 }
1023                 if (ip_hton(value, AF_INET, &ipaddr) < 0) {
1024                         radlog(L_ERR, "Can't find IP address for host %s", value);
1025                         return -1;
1026                 }
1027                 
1028                 if (strspn(value, "0123456789.") == strlen(value)) {
1029                         cf_log_info(cs, "\t%s = %s", name, value);
1030                 } else {
1031                         cf_log_info(cs, "\t%s = %s IP address [%s]", name, value,
1032                                ip_ntoh(&ipaddr, ipbuf, sizeof(ipbuf)));
1033                 }
1034                 *(uint32_t *) data = ipaddr.ipaddr.ip4addr.s_addr;
1035                 break;
1036
1037         case PW_TYPE_IPV6ADDR:
1038                 if (ip_hton(value, AF_INET6, &ipaddr) < 0) {
1039                         radlog(L_ERR, "Can't find IPv6 address for host %s", value);
1040                         return -1;
1041                 }
1042                 cf_log_info(cs, "\t%s = %s IPv6 address [%s]", name, value,
1043                                ip_ntoh(&ipaddr, ipbuf, sizeof(ipbuf)));
1044                 memcpy(data, &ipaddr.ipaddr.ip6addr,
1045                        sizeof(ipaddr.ipaddr.ip6addr));
1046                 break;
1047
1048         default:
1049                 radlog(L_ERR, "type %d not supported yet", type);
1050                 return -1;
1051         } /* switch over variable type */
1052
1053         if (!cp) {
1054                 CONF_PAIR *cpn;
1055
1056                 cpn = cf_pair_alloc(name, value, T_OP_SET, T_BARE_WORD, cs);
1057                 if (!cpn) return -1;
1058                 cpn->item.filename = "<internal>";
1059                 cpn->item.lineno = 0;
1060                 cf_item_add(cs, cf_pairtoitem(cpn));
1061         }
1062
1063         return rcode;
1064 }
1065
1066 static const char *parse_spaces = "                                                                                                                                                                                                                                                                ";
1067
1068 /*
1069  *      A copy of cf_section_parse that initializes pointers before
1070  *      parsing them.
1071  */
1072 static void cf_section_parse_init(CONF_SECTION *cs, void *base,
1073                                   const CONF_PARSER *variables)
1074 {
1075         int i;
1076         void *data;
1077
1078         for (i = 0; variables[i].name != NULL; i++) {
1079                 if (variables[i].type == PW_TYPE_SUBSECTION) {
1080                         CONF_SECTION *subcs;
1081                         subcs = cf_section_sub_find(cs, variables[i].name);
1082                         if (!subcs) continue;
1083
1084                         if (!variables[i].dflt) continue;
1085
1086                         cf_section_parse_init(subcs, base,
1087                                               (const CONF_PARSER *) variables[i].dflt);
1088                         continue;
1089                 }
1090
1091                 if ((variables[i].type != PW_TYPE_STRING_PTR) &&
1092                     (variables[i].type != PW_TYPE_FILENAME)) {
1093                         continue;
1094                 }
1095
1096                 if (variables[i].data) {
1097                         data = variables[i].data; /* prefer this. */
1098                 } else if (base) {
1099                         data = ((char *)base) + variables[i].offset;
1100                 } else {
1101                         continue;
1102                 }
1103
1104                 *(char **) data = NULL;
1105         } /* for all variables in the configuration section */
1106 }
1107
1108 /*
1109  *      Parse a configuration section into user-supplied variables.
1110  */
1111 int cf_section_parse(CONF_SECTION *cs, void *base,
1112                      const CONF_PARSER *variables)
1113 {
1114         int i;
1115         void *data;
1116
1117         cs->variables = variables; /* this doesn't hurt anything */
1118
1119         if (!cs->name2) {
1120                 cf_log_info(cs, "%.*s%s {", cs->depth, parse_spaces,
1121                        cs->name1);
1122         } else {
1123                 cf_log_info(cs, "%.*s%s %s {", cs->depth, parse_spaces,
1124                        cs->name1, cs->name2);
1125         }
1126
1127         cf_section_parse_init(cs, base, variables);
1128
1129         /*
1130          *      Handle the known configuration parameters.
1131          */
1132         for (i = 0; variables[i].name != NULL; i++) {
1133                 /*
1134                  *      Handle subsections specially
1135                  */
1136                 if (variables[i].type == PW_TYPE_SUBSECTION) {
1137                         CONF_SECTION *subcs;
1138                         subcs = cf_section_sub_find(cs, variables[i].name);
1139
1140                         /*
1141                          *      If the configuration section is NOT there,
1142                          *      then ignore it.
1143                          *
1144                          *      FIXME! This is probably wrong... we should
1145                          *      probably set the items to their default values.
1146                          */
1147                         if (!subcs) continue;
1148
1149                         if (!variables[i].dflt) {
1150                                 DEBUG2("Internal sanity check 1 failed in cf_section_parse");
1151                                 goto error;
1152                         }
1153
1154                         if (cf_section_parse(subcs, base,
1155                                              (const CONF_PARSER *) variables[i].dflt) < 0) {
1156                                 goto error;
1157                         }
1158                         continue;
1159                 } /* else it's a CONF_PAIR */
1160
1161                 if (variables[i].data) {
1162                         data = variables[i].data; /* prefer this. */
1163                 } else if (base) {
1164                         data = ((char *)base) + variables[i].offset;
1165                 } else {
1166                         DEBUG2("Internal sanity check 2 failed in cf_section_parse");
1167                         goto error;
1168                 }
1169
1170                 /*
1171                  *      Parse the pair we found, or a default value.
1172                  */
1173                 if (cf_item_parse(cs, variables[i].name, variables[i].type,
1174                                   data, variables[i].dflt) < 0) {
1175                         goto error;
1176                 }
1177         } /* for all variables in the configuration section */
1178
1179         cf_log_info(cs, "%.*s}", cs->depth, parse_spaces);
1180
1181         cs->base = base;
1182
1183         return 0;
1184
1185  error:
1186         cf_log_info(cs, "%.*s}", cs->depth, parse_spaces);
1187         cf_section_parse_free(cs, base);
1188         return -1;
1189 }
1190
1191
1192 /*
1193  *      Sanity check the "if" or "elsif", presuming that the first '('
1194  *      has already been eaten.
1195  *
1196  *      We're not really parsing it here, just checking if it's mostly
1197  *      well-formed.
1198  */
1199 static int condition_looks_ok(const char **ptr)
1200 {
1201         int num_braces = 1;
1202         int quote = 0;
1203         const char *p = *ptr;
1204
1205         while (*p) {
1206                 if (quote) {
1207                         if (*p == quote) {
1208                                 p++;
1209                                 quote = 0;
1210                                 continue;
1211                         }
1212
1213                         if (*p == '\\') {
1214                                 if (!p[1]) {
1215                                         return 0; /* no trailing slash */
1216                                 }
1217                                 p += 2;
1218                                 continue;
1219                         }
1220                         p++;
1221                         continue;
1222                 }
1223
1224                 switch (*p) {
1225                 case '\\':
1226                         if (!p[1]) {
1227                                 return 0; /* no trailing slash */
1228                         }
1229                         p += 2;
1230                         continue;
1231
1232                 case '(':
1233                         num_braces++;
1234                         p++;
1235                         continue;
1236
1237                 case ')':
1238                         if (num_braces == 1) {
1239                                 const char *q = p + 1;
1240
1241                                 /*
1242                                  *      Validate that there isn't much
1243                                  *      else after the closing brace.
1244                                  */
1245                                 while ((*q == ' ') || (*q == '\t')) q++;
1246
1247                                 /*
1248                                  *      Parse error.
1249                                  */
1250                                 if (*q != '{') {
1251                                         DEBUG2("Expected open brace '{' after condition at %s", p);
1252                                         return 0;
1253                                 }
1254
1255                                 *ptr = p + 1; /* include the trailing ')' */
1256                                 return 1;
1257                         }
1258                         num_braces--;
1259                         p++;
1260                         continue;
1261
1262                 case '"':
1263                 case '\'':
1264                 case '/':
1265                 case '`':
1266                         quote = *p;
1267                         /* FALL-THROUGH */
1268
1269                 default:
1270                         p++;
1271                         break;
1272                 }
1273         }
1274
1275         DEBUG3("Unexpected error");
1276         return 0;
1277 }
1278
1279 int cf_exclude_file(const char *filename)
1280 {
1281         int i;
1282         size_t len;
1283         const char *p = filename;
1284
1285         /*
1286          *      FIXME: Maybe later make this a globally set configuration
1287          *      variable.  But that's low priority.
1288          */
1289         static const char *excluded[] = {
1290                 "rpmsave", "rpmnew", "dpkg-new", "dpkg-dist", "dpkg-old",
1291                 "bak", NULL
1292         };
1293
1294         if (!p || !*p) return TRUE; /* coding error */
1295
1296         if (*p == '.') return TRUE; /* ".", "..", ".foo", ... */
1297
1298         if (*p == '#') return TRUE; /* #foo# */
1299
1300         len = strlen(p);
1301         if (p[len - 1] == '~') return TRUE; /* foo~ */
1302
1303         p = strrchr(p, '.');
1304         if (!p) return FALSE;   /* just "foo", it's OK */
1305
1306         p++;
1307         for (i = 0; excluded[i] != NULL; i++) {
1308                 if (strcmp(p, excluded[i]) == 0) return TRUE;
1309         }
1310
1311         return FALSE;
1312 }
1313
1314
1315 static const char *cf_local_file(CONF_SECTION *cs, const char *local,
1316                                  char *buffer, size_t bufsize)
1317 {
1318         size_t dirsize;
1319         const char *p;
1320         CONF_SECTION *parentcs = cf_top_section(cs);
1321
1322         p = strrchr(parentcs->item.filename, FR_DIR_SEP);
1323         if (!p) return local;
1324
1325         dirsize = (p - parentcs->item.filename) + 1;
1326
1327         if ((dirsize + strlen(local)) >= bufsize) {
1328                 return NULL;
1329         }
1330
1331         memcpy(buffer, parentcs->item.filename, dirsize);
1332         strlcpy(buffer + dirsize, local, bufsize - dirsize);
1333
1334         return buffer;
1335 }
1336
1337 static int seen_too_much(const char *filename, int lineno, const char *ptr)
1338 {
1339         while (*ptr) {
1340                 if (isspace(*ptr)) {
1341                         ptr++;
1342                         continue;
1343                 }
1344
1345                 if (*ptr == '#') return FALSE;
1346
1347                 break;
1348         }
1349
1350         if (*ptr) {
1351                 radlog(L_ERR, "%s[%d] Unexpected text %s.  See \"man unlang\"",
1352                        filename, lineno, ptr);
1353                 return TRUE;
1354         }
1355
1356         return FALSE;
1357 }
1358
1359
1360 /*
1361  *      Read a part of the config file.
1362  */
1363 static int cf_section_read(const char *filename, int *lineno, FILE *fp,
1364                            CONF_SECTION *current)
1365
1366 {
1367         CONF_SECTION *this, *css;
1368         CONF_PAIR *cpn;
1369         const char *ptr;
1370         const char *value;
1371         char buf[8192];
1372         char buf1[8192];
1373         char buf2[8192];
1374         char buf3[8192];
1375         int t1, t2, t3;
1376         char *cbuf = buf;
1377         size_t len;
1378
1379         this = current;         /* add items here */
1380
1381         /*
1382          *      Read, checking for line continuations ('\\' at EOL)
1383          */
1384         for (;;) {
1385                 int at_eof;
1386
1387                 /*
1388                  *      Get data, and remember if we are at EOF.
1389                  */
1390                 at_eof = (fgets(cbuf, sizeof(buf) - (cbuf - buf), fp) == NULL);
1391                 (*lineno)++;
1392
1393                 /*
1394                  *      We read the entire 8k worth of data: complain.
1395                  *      Note that we don't care if the last character
1396                  *      is \n: it's still forbidden.  This means that
1397                  *      the maximum allowed length of text is 8k-1, which
1398                  *      should be plenty.
1399                  */
1400                 len = strlen(cbuf);
1401                 if ((cbuf + len + 1) >= (buf + sizeof(buf))) {
1402                         radlog(L_ERR, "%s[%d]: Line too long",
1403                                filename, *lineno);
1404                         return -1;
1405                 }
1406
1407                 /*
1408                  *      Not doing continuations: check for edge
1409                  *      conditions.
1410                  */
1411                 if (cbuf == buf) {
1412                         if (at_eof) break;
1413                         
1414                         ptr = buf;
1415                         while (*ptr && isspace((int) *ptr)) ptr++;
1416
1417                         if (!*ptr || (*ptr == '#')) continue;
1418
1419                 } else if (at_eof || (len == 0)) {
1420                         radlog(L_ERR, "%s[%d]: Continuation at EOF is illegal",
1421                                filename, *lineno);
1422                         return -1;
1423                 }
1424
1425                 /*
1426                  *      See if there's a continuation.
1427                  */
1428                 while ((len > 0) &&
1429                        ((cbuf[len - 1] == '\n') || (cbuf[len - 1] == '\r'))) {
1430                         len--;
1431                         cbuf[len] = '\0';
1432                 }
1433
1434                 if ((len > 0) && (cbuf[len - 1] == '\\')) {
1435                         cbuf[len - 1] = '\0';
1436                         cbuf += len - 1;
1437                         continue;
1438                 }
1439
1440                 ptr = cbuf = buf;
1441
1442                 /*
1443                  *      The parser is getting to be evil.
1444                  */
1445                 while ((*ptr == ' ') || (*ptr == '\t')) ptr++;
1446
1447                 if (((ptr[0] == '%') && (ptr[1] == '{')) ||
1448                     (ptr[0] == '`')) {
1449                         int hack;
1450
1451                         if (ptr[0] == '%') {
1452                                 hack = rad_copy_variable(buf1, ptr);
1453                         } else {
1454                                 hack = rad_copy_string(buf1, ptr);
1455                         }
1456                         if (hack < 0) {
1457                                 radlog(L_ERR, "%s[%d]: Invalid expansion: %s",
1458                                        filename, *lineno, ptr);
1459                                 return -1;
1460                         }
1461
1462                         t1 = T_BARE_WORD;
1463                         ptr += hack;
1464
1465                         t2 = gettoken(&ptr, buf2, sizeof(buf2));
1466                         switch (t2) {
1467                         case T_EOL:
1468                         case T_HASH:
1469                                 goto do_bare_word;
1470                                 
1471                         default:
1472                                 radlog(L_ERR, "%s[%d]: Invalid expansion: %s",
1473                                        filename, *lineno, ptr);
1474                                 return -1;
1475                         }
1476                 } else {
1477                         t1 = gettoken(&ptr, buf1, sizeof(buf1));
1478                 }
1479
1480                 /*
1481                  *      The caller eats "name1 name2 {", and calls us
1482                  *      for the data inside of the section.  So if we
1483                  *      receive a closing brace, then it must mean the
1484                  *      end of the section.
1485                  */
1486                if (t1 == T_RCBRACE) {
1487                        if (this == current) {
1488                                radlog(L_ERR, "%s[%d]: Too many closing braces",
1489                                       filename, *lineno);
1490                                return -1;
1491
1492                        }
1493                        this = this->item.parent;
1494                        if (seen_too_much(filename, *lineno, ptr)) return -1;
1495                        continue;
1496                 }
1497
1498                 /*
1499                  *      Allow for $INCLUDE files
1500                  *
1501                  *      This *SHOULD* work for any level include.
1502                  *      I really really really hate this file.  -cparker
1503                  */
1504                if ((strcasecmp(buf1, "$INCLUDE") == 0) ||
1505                    (strcasecmp(buf1, "$-INCLUDE") == 0)) {
1506                        int relative = 1;
1507
1508                         t2 = getword(&ptr, buf2, sizeof(buf2));
1509
1510                         if (buf2[0] == '$') relative = 0;
1511
1512                         value = cf_expand_variables(filename, lineno, this, buf, sizeof(buf), buf2);
1513                         if (!value) return -1;
1514
1515                         if (!FR_DIR_IS_RELATIVE(value)) relative = 0;
1516
1517                         if (relative) {
1518                                 value = cf_local_file(current, value, buf3,
1519                                                       sizeof(buf3));
1520                                 if (!value) {
1521                                         radlog(L_ERR, "%s[%d]: Directories too deep.",
1522                                                filename, *lineno);
1523                                         return -1;
1524                                 }
1525                         }
1526
1527
1528 #ifdef HAVE_DIRENT_H
1529                         /*
1530                          *      $INCLUDE foo/
1531                          *
1532                          *      Include ALL non-"dot" files in the directory.
1533                          *      careful!
1534                          */
1535                         if (value[strlen(value) - 1] == '/') {
1536                                 DIR             *dir;
1537                                 struct dirent   *dp;
1538                                 struct stat stat_buf;
1539
1540                                 DEBUG2("including files in directory %s", value );
1541 #ifdef S_IWOTH
1542                                 /*
1543                                  *      Security checks.
1544                                  */
1545                                 if (stat(value, &stat_buf) < 0) {
1546                                         radlog(L_ERR, "%s[%d]: Failed reading directory %s: %s",
1547                                                filename, *lineno, 
1548                                                value, strerror(errno));
1549                                         return -1;
1550                                 }
1551
1552                                 if ((stat_buf.st_mode & S_IWOTH) != 0) {
1553                                         radlog(L_ERR|L_CONS, "%s[%d]: Directory %s is globally writable.  Refusing to start due to insecure configuration.",
1554                                                filename, *lineno, value);
1555                                         return -1;
1556                                 }
1557 #endif
1558                                 dir = opendir(value);
1559                                 if (!dir) {
1560                                         radlog(L_ERR, "%s[%d]: Error reading directory %s: %s",
1561                                                filename, *lineno, value,
1562                                                strerror(errno));
1563                                         return -1;
1564                                 }
1565
1566                                 /*
1567                                  *      Read the directory, ignoring some files.
1568                                  */
1569                                 while ((dp = readdir(dir)) != NULL) {
1570                                         if (cf_exclude_file(dp->d_name))
1571                                                 continue;
1572
1573                                         snprintf(buf2, sizeof(buf2), "%s%s",
1574                                                  value, dp->d_name);
1575                                         if ((stat(buf2, &stat_buf) != 0) ||
1576                                             S_ISDIR(stat_buf.st_mode)) continue;
1577                                         /*
1578                                          *      Read the file into the current
1579                                          *      configuration sectoin.
1580                                          */
1581                                         if (cf_file_include(buf2, this) < 0) {
1582                                                 closedir(dir);
1583                                                 return -1;
1584                                         }
1585                                 }
1586                                 closedir(dir);
1587                         }  else
1588 #endif
1589                         { /* it was a normal file */
1590                                 if (buf1[1] == '-') {
1591                                         struct stat statbuf;
1592
1593                                         if (stat(value, &statbuf) < 0) {
1594                                                 DEBUG("WARNING: Not including file %s: %s", value, strerror(errno));
1595                                                 continue;
1596                                         }
1597                                 }
1598
1599                                 if (cf_file_include(value, this) < 0) {
1600                                         return -1;
1601                                 }
1602                         }
1603                         continue;
1604                 } /* we were in an include */
1605
1606                if (strcasecmp(buf1, "$template") == 0) {
1607                        CONF_ITEM *ci;
1608                        CONF_SECTION *parentcs, *templatecs;
1609                        t2 = getword(&ptr, buf2, sizeof(buf2));
1610
1611                        parentcs = cf_top_section(current);
1612
1613                        templatecs = cf_section_sub_find(parentcs, "templates");
1614                        if (!templatecs) {
1615                                 radlog(L_ERR, "%s[%d]: No \"templates\" section for reference \"%s\"",
1616                                        filename, *lineno, buf2);
1617                                 return -1;
1618                        }
1619
1620                        ci = cf_reference_item(parentcs, templatecs, buf2);
1621                        if (!ci || (ci->type != CONF_ITEM_SECTION)) {
1622                                 radlog(L_ERR, "%s[%d]: Reference \"%s\" not found",
1623                                        filename, *lineno, buf2);
1624                                 return -1;
1625                        }
1626                        
1627                        if (this->template) {
1628                                 radlog(L_ERR, "%s[%d]: Section already has a template",
1629                                        filename, *lineno);
1630                                 return -1;
1631                        }
1632
1633                        this->template = cf_itemtosection(ci);
1634                        continue;
1635                }
1636
1637                 /*
1638                  *      Ensure that the user can't add CONF_PAIRs
1639                  *      with 'internal' names;
1640                  */
1641                 if (buf1[0] == '_') {
1642                         radlog(L_ERR, "%s[%d]: Illegal configuration pair name \"%s\"",
1643                                         filename, *lineno, buf1);
1644                         return -1;
1645                 }
1646
1647                 /*
1648                  *      Grab the next token.
1649                  */
1650                 t2 = gettoken(&ptr, buf2, sizeof(buf2));
1651                 switch (t2) {
1652                 case T_EOL:
1653                 case T_HASH:
1654                 do_bare_word:
1655                         t3 = t2;
1656                         t2 = T_OP_EQ;
1657                         value = NULL;
1658                         goto do_set;
1659
1660                 case T_OP_ADD:
1661                 case T_OP_CMP_EQ:
1662                 case T_OP_SUB:
1663                 case T_OP_LE:
1664                 case T_OP_GE:
1665                 case T_OP_CMP_FALSE:
1666                         if (!this || (strcmp(this->name1, "update") != 0)) {
1667                                 radlog(L_ERR, "%s[%d]: Invalid operator in assignment",
1668                                        filename, *lineno);
1669                                 return -1;
1670                         }
1671                         /* FALL-THROUGH */
1672
1673                 case T_OP_EQ:
1674                 case T_OP_SET:
1675                         t3 = getstring(&ptr, buf3, sizeof(buf3));
1676                         if (t3 == T_OP_INVALID) {
1677                                 radlog(L_ERR, "%s[%d]: Parse error: %s",
1678                                        filename, *lineno,
1679                                        fr_strerror());
1680                                 return -1;
1681                         }
1682
1683                         /*
1684                          *      These are not allowed.  Print a
1685                          *      helpful error message.
1686                          */
1687                         if ((t3 == T_BACK_QUOTED_STRING) &&
1688                             (!this || (strcmp(this->name1, "update") != 0))) {
1689                                 radlog(L_ERR, "%s[%d]: Syntax error: Invalid string `...` in assignment",
1690                                        filename, *lineno);
1691                                 return -1;
1692                         }
1693
1694                         /*
1695                          *      Handle variable substitution via ${foo}
1696                          */
1697                         if ((t3 == T_BARE_WORD) ||
1698                             (t3 == T_DOUBLE_QUOTED_STRING)) {
1699                                 value = cf_expand_variables(filename, lineno, this,
1700                                                             buf, sizeof(buf), buf3);
1701                                 if (!value) return -1;
1702                         } else if ((t3 == T_EOL) ||
1703                                    (t3 == T_HASH)) {
1704                                 value = NULL;
1705                         } else {
1706                                 value = buf3;
1707                         }
1708                         
1709                         /*
1710                          *      Add this CONF_PAIR to our CONF_SECTION
1711                          */
1712                 do_set:
1713                         cpn = cf_pair_alloc(buf1, value, t2, t3, this);
1714                         cpn->item.filename = filename;
1715                         cpn->item.lineno = *lineno;
1716                         cf_item_add(this, cf_pairtoitem(cpn));
1717                         continue;
1718
1719                         /*
1720                          *      This horrible code is here to support
1721                          *      if/then/else failover in the
1722                          *      authorize, etc. sections.  It makes no
1723                          *      sense anywhere else.
1724                          */
1725                 case T_LBRACE:
1726                         if ((strcmp(buf1, "if") == 0) ||
1727                             (strcmp(buf1, "elsif") == 0)) {
1728                                 const char *end = ptr;
1729                                 CONF_SECTION *server;
1730
1731                                 if (!condition_looks_ok(&end)) {
1732                                         radlog(L_ERR, "%s[%d]: Parse error in condition at: %s",
1733                                                filename, *lineno, ptr);
1734                                         return -1;
1735                                 }
1736
1737                                 if ((size_t) (end - ptr) >= (sizeof(buf2) - 1)) {
1738                                         radlog(L_ERR, "%s[%d]: Statement too complicated after \"%s\"",
1739                                                filename, *lineno, buf1);
1740                                         return -1;
1741                                 }
1742
1743                                 /*
1744                                  *      More sanity checking.  This is
1745                                  *      getting to be a horrible hack.
1746                                  */
1747                                 server = this;
1748                                 while (server) {
1749                                         if (strcmp(server->name1, "server") == 0) break;
1750                                         server = server->item.parent;
1751                                 }
1752                                 
1753                                 if (0 && !server) {
1754                                         radlog(L_ERR, "%s[%d]: Processing directives such as \"%s\" cannot be used here.",
1755                                                filename, *lineno, buf1);
1756                                         return -1;
1757                                 }
1758
1759                                 buf2[0] = '(';
1760                                 memcpy(buf2 + 1, ptr, end - ptr);
1761                                 buf2[end - ptr + 1] = '\0';
1762                                 ptr = end;
1763                                 t2 = T_BARE_WORD;
1764
1765                                 if (gettoken(&ptr, buf3, sizeof(buf3)) != T_LCBRACE) {
1766                                         radlog(L_ERR, "%s[%d]: Expected '{'",
1767                                                filename, *lineno);
1768                                         return -1;
1769                                 }
1770                                 goto section_alloc;
1771
1772                         } else {
1773                                 radlog(L_ERR, "%s[%d]: Parse error after \"%s\"",
1774                                        filename, *lineno, buf1);
1775                                 return -1;
1776                         }
1777
1778                         /* FALL-THROUGH */
1779
1780                         /*
1781                          *      No '=', must be a section or sub-section.
1782                          */
1783                 case T_BARE_WORD:
1784                 case T_DOUBLE_QUOTED_STRING:
1785                 case T_SINGLE_QUOTED_STRING:
1786                         t3 = gettoken(&ptr, buf3, sizeof(buf3));
1787                         if (t3 != T_LCBRACE) {
1788                                 radlog(L_ERR, "%s[%d]: Expecting section start brace '{' after \"%s %s\"",
1789                                        filename, *lineno, buf1, buf2);
1790                                 return -1;
1791                         }
1792                         /* FALL-THROUGH */
1793
1794                 case T_LCBRACE:
1795                 section_alloc:
1796                         if (seen_too_much(filename, *lineno, ptr)) return -1;
1797
1798                         css = cf_section_alloc(buf1,
1799                                                t2 == T_LCBRACE ? NULL : buf2,
1800                                                this);
1801                         if (!css) {
1802                                 radlog(L_ERR, "%s[%d]: Failed allocating memory for section",
1803                                                 filename, *lineno);
1804                                 return -1;
1805                         }
1806                         cf_item_add(this, cf_sectiontoitem(css));
1807                         css->item.filename = filename;
1808                         css->item.lineno = *lineno;
1809
1810                         /*
1811                          *      The current section is now the child section.
1812                          */
1813                         this = css;
1814                         continue;
1815
1816                 default:
1817                         radlog(L_ERR, "%s[%d]: Parse error after \"%s\"",
1818                                filename, *lineno, buf1);
1819                         return -1;
1820                 }
1821         }
1822
1823         /*
1824          *      See if EOF was unexpected ..
1825          */
1826         if (feof(fp) && (this != current)) {
1827                 radlog(L_ERR, "%s[%d]: EOF reached without closing brace for section %s starting at line %d",
1828                        filename, *lineno,
1829                        cf_section_name1(this), cf_section_lineno(this));
1830                 return -1;
1831         }
1832
1833         return 0;
1834 }
1835
1836 /*
1837  *      Include one config file in another.
1838  */
1839 int cf_file_include(const char *filename, CONF_SECTION *cs)
1840 {
1841         FILE            *fp;
1842         int             lineno = 0;
1843         struct stat     statbuf;
1844         time_t          *mtime;
1845         CONF_DATA       *cd;
1846
1847         DEBUG2( "including configuration file %s", filename);
1848
1849         if (stat(filename, &statbuf) == 0) {
1850 #ifdef S_IWOTH
1851                 if ((statbuf.st_mode & S_IWOTH) != 0) {
1852                         radlog(L_ERR|L_CONS, "Configuration file %s is globally writable.  Refusing to start due to insecure configuration.",
1853                                filename);
1854                         return -1;
1855                 }
1856 #endif
1857
1858 #ifdef S_IROTH
1859                 if (0 && (statbuf.st_mode & S_IROTH) != 0) {
1860                         radlog(L_ERR|L_CONS, "Configuration file %s is globally readable.  Refusing to start due to insecure configuration.",
1861                                filename);
1862                         return -1;
1863                 }
1864 #endif
1865         }
1866
1867         fp = fopen(filename, "r");
1868         if (!fp) {
1869                 radlog(L_ERR|L_CONS, "Unable to open file \"%s\": %s",
1870                        filename, strerror(errno));
1871                 return -1;
1872         }
1873
1874         if (cf_data_find_internal(cs, filename, PW_TYPE_FILENAME)) {
1875                 fclose(fp);
1876                 radlog(L_ERR, "Cannot include the same file twice: \"%s\"",
1877                        filename);
1878                 return -1;
1879         }
1880
1881         /*
1882          *      Add the filename to the section
1883          */
1884         mtime = rad_malloc(sizeof(*mtime));
1885         *mtime = statbuf.st_mtime;
1886
1887         if (cf_data_add_internal(cs, filename, mtime, free,
1888                                  PW_TYPE_FILENAME) < 0) {
1889                 fclose(fp);
1890                 radlog(L_ERR|L_CONS, "Internal error opening file \"%s\"",
1891                        filename);
1892                 return -1;
1893         }
1894
1895         cd = cf_data_find_internal(cs, filename, PW_TYPE_FILENAME);
1896         if (!cd) {
1897                 fclose(fp);
1898                 radlog(L_ERR|L_CONS, "Internal error opening file \"%s\"",
1899                        filename);
1900                 return -1;
1901         }
1902
1903         if (!cs->item.filename) cs->item.filename = filename;
1904
1905         /*
1906          *      Read the section.  It's OK to have EOF without a
1907          *      matching close brace.
1908          */
1909         if (cf_section_read(cd->name, &lineno, fp, cs) < 0) {
1910                 fclose(fp);
1911                 return -1;
1912         }
1913
1914         fclose(fp);
1915         return 0;
1916 }
1917
1918 /*
1919  *      Bootstrap a config file.
1920  */
1921 CONF_SECTION *cf_file_read(const char *filename)
1922 {
1923         char *p;
1924         CONF_PAIR *cp;
1925         CONF_SECTION *cs;
1926
1927         cs = cf_section_alloc("main", NULL, NULL);
1928         if (!cs) return NULL;
1929
1930         cp = cf_pair_alloc("confdir", filename, T_OP_SET, T_BARE_WORD, cs);
1931         if (!cp) return NULL;
1932
1933         p = strrchr(cp->value, FR_DIR_SEP);
1934         if (p) *p = '\0';
1935
1936         cp->item.filename = "internal";
1937         cp->item.lineno = 0;
1938         cf_item_add(cs, cf_pairtoitem(cp));
1939
1940         if (cf_file_include(filename, cs) < 0) {
1941                 cf_section_free(&cs);
1942                 return NULL;
1943         }
1944
1945         return cs;
1946 }
1947
1948 /*
1949  * Return a CONF_PAIR within a CONF_SECTION.
1950  */
1951 CONF_PAIR *cf_pair_find(const CONF_SECTION *cs, const char *name)
1952 {
1953         CONF_ITEM       *ci;
1954         CONF_PAIR       *cp = NULL;
1955
1956         if (!cs) return NULL;
1957
1958         /*
1959          *      Find the name in the tree, for speed.
1960          */
1961         if (name) {
1962                 CONF_PAIR mycp;
1963
1964                 mycp.attr = name;
1965                 cp = rbtree_finddata(cs->pair_tree, &mycp);
1966         } else {
1967                 /*
1968                  *      Else find the first one that matches
1969                  */
1970                 for (ci = cs->children; ci; ci = ci->next) {
1971                         if (ci->type == CONF_ITEM_PAIR) {
1972                                 return cf_itemtopair(ci);
1973                         }
1974                 }
1975         }
1976
1977         if (cp || !cs->template) return cp;
1978
1979         return cf_pair_find(cs->template, name);
1980 }
1981
1982 /*
1983  * Return the attr of a CONF_PAIR
1984  */
1985
1986 const char *cf_pair_attr(CONF_PAIR *pair)
1987 {
1988         return (pair ? pair->attr : NULL);
1989 }
1990
1991 /*
1992  * Return the value of a CONF_PAIR
1993  */
1994
1995 const char *cf_pair_value(CONF_PAIR *pair)
1996 {
1997         return (pair ? pair->value : NULL);
1998 }
1999
2000 FR_TOKEN cf_pair_operator(CONF_PAIR *pair)
2001 {
2002         return (pair ? pair->operator : T_OP_INVALID);
2003 }
2004
2005 /*
2006  *      Copied here for error reporting.
2007  */
2008 extern void fr_strerror_printf(const char *, ...);
2009
2010 /*
2011  * Turn a CONF_PAIR into a VALUE_PAIR
2012  * For now, ignore the "value_type" field...
2013  */
2014 VALUE_PAIR *cf_pairtovp(CONF_PAIR *pair)
2015 {
2016         VALUE_PAIR *vp;
2017
2018         if (!pair) {
2019                 fr_strerror_printf("Internal error");
2020                 return NULL;
2021         }
2022
2023         if (!pair->value) {
2024                 fr_strerror_printf("No value given for attribute %s", pair->attr);
2025                 return NULL;
2026         }
2027
2028         /*
2029          *      pairmake handles tags.  pairalloc() doesn't.
2030          */
2031         vp = pairmake(pair->attr, NULL, pair->operator);
2032         if (!vp) {
2033                 return NULL;
2034         }
2035
2036         /*
2037          *      Ignore the value if it's a false comparison.
2038          */
2039         if (pair->operator == T_OP_CMP_FALSE) return vp;
2040
2041         if (pair->value_type == T_BARE_WORD) {
2042                 if ((vp->type == PW_TYPE_STRING) && 
2043                     (pair->value[0] == '0') && (pair->value[1] == 'x')) {
2044                         vp->type = PW_TYPE_OCTETS;
2045                 }
2046                 if (!pairparsevalue(vp, pair->value)) {
2047                         pairfree(&vp);
2048                         return NULL;
2049                 }
2050                 vp->flags.do_xlat = 0;
2051           
2052         } else if (pair->value_type == T_SINGLE_QUOTED_STRING) {
2053                 if (!pairparsevalue(vp, pair->value)) {
2054                         pairfree(&vp);
2055                         return NULL;
2056                 }
2057                 vp->flags.do_xlat = 0;
2058         } else {
2059                 vp->flags.do_xlat = 1;
2060         }
2061
2062         return vp;
2063 }
2064
2065 /*
2066  * Return the first label of a CONF_SECTION
2067  */
2068
2069 const char *cf_section_name1(const CONF_SECTION *cs)
2070 {
2071         return (cs ? cs->name1 : NULL);
2072 }
2073
2074 /*
2075  * Return the second label of a CONF_SECTION
2076  */
2077
2078 const char *cf_section_name2(const CONF_SECTION *cs)
2079 {
2080         return (cs ? cs->name2 : NULL);
2081 }
2082
2083 /*
2084  * Find a value in a CONF_SECTION
2085  */
2086 const char *cf_section_value_find(const CONF_SECTION *cs, const char *attr)
2087 {
2088         CONF_PAIR       *cp;
2089
2090         cp = cf_pair_find(cs, attr);
2091
2092         return (cp ? cp->value : NULL);
2093 }
2094
2095
2096 CONF_SECTION *cf_section_find_name2(const CONF_SECTION *section,
2097                                     const char *name1, const char *name2)
2098 {
2099         const char      *their2;
2100         CONF_ITEM       *ci;
2101
2102         if (!section || !name1) return NULL;
2103
2104         for (ci = cf_sectiontoitem(section); ci; ci = ci->next) {
2105                 if (ci->type != CONF_ITEM_SECTION)
2106                         continue;
2107
2108                 if (strcmp(cf_itemtosection(ci)->name1, name1) != 0)
2109                         continue;
2110
2111                 their2 = cf_itemtosection(ci)->name2;
2112
2113                 if ((!name2 && !their2) ||
2114                     (name2 && their2 && (strcmp(name2, their2) == 0))) {
2115                         return cf_itemtosection(ci);
2116                 }
2117         }
2118         
2119         return NULL;
2120 }
2121
2122 /*
2123  * Return the next pair after a CONF_PAIR
2124  * with a certain name (char *attr) If the requested
2125  * attr is NULL, any attr matches.
2126  */
2127
2128 CONF_PAIR *cf_pair_find_next(const CONF_SECTION *cs,
2129                              CONF_PAIR *pair, const char *attr)
2130 {
2131         CONF_ITEM       *ci;
2132
2133         if (!cs) return NULL;
2134
2135         /*
2136          * If pair is NULL this must be a first time run
2137          * Find the pair with correct name
2138          */
2139
2140         if (pair == NULL){
2141                 return cf_pair_find(cs, attr);
2142         }
2143
2144         ci = cf_pairtoitem(pair)->next;
2145
2146         for (; ci; ci = ci->next) {
2147                 if (ci->type != CONF_ITEM_PAIR)
2148                         continue;
2149                 if (attr == NULL || strcmp(cf_itemtopair(ci)->attr, attr) == 0)
2150                         break;
2151         }
2152
2153         return cf_itemtopair(ci);
2154 }
2155
2156 /*
2157  * Find a CONF_SECTION, or return the root if name is NULL
2158  */
2159
2160 CONF_SECTION *cf_section_find(const char *name)
2161 {
2162         if (name)
2163                 return cf_section_sub_find(mainconfig.config, name);
2164         else
2165                 return mainconfig.config;
2166 }
2167
2168 /*
2169  * Find a sub-section in a section
2170  */
2171
2172 CONF_SECTION *cf_section_sub_find(const CONF_SECTION *cs, const char *name)
2173 {
2174         CONF_ITEM *ci;
2175
2176         if (!name) return NULL; /* can't find an un-named section */
2177
2178         /*
2179          *      Do the fast lookup if possible.
2180          */
2181         if (cs->section_tree) {
2182                 CONF_SECTION mycs;
2183
2184                 mycs.name1 = name;
2185                 mycs.name2 = NULL;
2186                 return rbtree_finddata(cs->section_tree, &mycs);
2187         }
2188
2189         for (ci = cs->children; ci; ci = ci->next) {
2190                 if (ci->type != CONF_ITEM_SECTION)
2191                         continue;
2192                 if (strcmp(cf_itemtosection(ci)->name1, name) == 0)
2193                         break;
2194         }
2195
2196         return cf_itemtosection(ci);
2197
2198 }
2199
2200
2201 /*
2202  *      Find a CONF_SECTION with both names.
2203  */
2204 CONF_SECTION *cf_section_sub_find_name2(const CONF_SECTION *cs,
2205                                         const char *name1, const char *name2)
2206 {
2207         CONF_ITEM    *ci;
2208
2209         if (!cs) cs = mainconfig.config;
2210
2211         if (name1 && (cs->section_tree)) {
2212                 CONF_SECTION mycs, *master_cs;
2213
2214                 mycs.name1 = name1;
2215                 mycs.name2 = name2;
2216
2217                 master_cs = rbtree_finddata(cs->section_tree, &mycs);
2218                 if (master_cs) {
2219                         return rbtree_finddata(master_cs->name2_tree, &mycs);
2220                 }
2221         }
2222
2223         /*
2224          *      Else do it the old-fashioned way.
2225          */
2226         for (ci = cs->children; ci; ci = ci->next) {
2227                 CONF_SECTION *subcs;
2228
2229                 if (ci->type != CONF_ITEM_SECTION)
2230                         continue;
2231
2232                 subcs = cf_itemtosection(ci);
2233                 if (!name1) {
2234                         if (!subcs->name2) {
2235                                 if (strcmp(subcs->name1, name2) == 0) break;
2236                         } else {
2237                                 if (strcmp(subcs->name2, name2) == 0) break;
2238                         }
2239                         continue; /* don't do the string comparisons below */
2240                 }
2241
2242                 if ((strcmp(subcs->name1, name1) == 0) &&
2243                     (subcs->name2 != NULL) &&
2244                     (strcmp(subcs->name2, name2) == 0))
2245                         break;
2246         }
2247
2248         return cf_itemtosection(ci);
2249 }
2250
2251 /*
2252  * Return the next subsection after a CONF_SECTION
2253  * with a certain name1 (char *name1). If the requested
2254  * name1 is NULL, any name1 matches.
2255  */
2256
2257 CONF_SECTION *cf_subsection_find_next(CONF_SECTION *section,
2258                                       CONF_SECTION *subsection,
2259                                       const char *name1)
2260 {
2261         CONF_ITEM       *ci;
2262
2263         if (!section) return NULL;
2264
2265         /*
2266          * If subsection is NULL this must be a first time run
2267          * Find the subsection with correct name
2268          */
2269
2270         if (subsection == NULL){
2271                 ci = section->children;
2272         } else {
2273                 ci = cf_sectiontoitem(subsection)->next;
2274         }
2275
2276         for (; ci; ci = ci->next) {
2277                 if (ci->type != CONF_ITEM_SECTION)
2278                         continue;
2279                 if ((name1 == NULL) ||
2280                     (strcmp(cf_itemtosection(ci)->name1, name1) == 0))
2281                         break;
2282         }
2283
2284         return cf_itemtosection(ci);
2285 }
2286
2287
2288 /*
2289  * Return the next section after a CONF_SECTION
2290  * with a certain name1 (char *name1). If the requested
2291  * name1 is NULL, any name1 matches.
2292  */
2293
2294 CONF_SECTION *cf_section_find_next(CONF_SECTION *section,
2295                                    CONF_SECTION *subsection,
2296                                    const char *name1)
2297 {
2298         if (!section) return NULL;
2299
2300         if (!section->item.parent) return NULL;
2301
2302         return cf_subsection_find_next(section->item.parent, subsection, name1);
2303 }
2304
2305 /*
2306  * Return the next item after a CONF_ITEM.
2307  */
2308
2309 CONF_ITEM *cf_item_find_next(CONF_SECTION *section, CONF_ITEM *item)
2310 {
2311         if (!section) return NULL;
2312
2313         /*
2314          * If item is NULL this must be a first time run
2315          * Return the first item
2316          */
2317
2318         if (item == NULL) {
2319                 return section->children;
2320         } else {
2321                 return item->next;
2322         }
2323 }
2324
2325 CONF_SECTION *cf_item_parent(CONF_ITEM *ci)
2326 {
2327         if (!ci) return NULL;
2328
2329         return ci->parent;
2330 }
2331
2332 int cf_section_lineno(CONF_SECTION *section)
2333 {
2334         return cf_sectiontoitem(section)->lineno;
2335 }
2336
2337 const char *cf_pair_filename(CONF_PAIR *pair)
2338 {
2339         return cf_pairtoitem(pair)->filename;
2340 }
2341
2342 const char *cf_section_filename(CONF_SECTION *section)
2343 {
2344         return cf_sectiontoitem(section)->filename;
2345 }
2346
2347 int cf_pair_lineno(CONF_PAIR *pair)
2348 {
2349         return cf_pairtoitem(pair)->lineno;
2350 }
2351
2352 int cf_item_is_section(CONF_ITEM *item)
2353 {
2354         return item->type == CONF_ITEM_SECTION;
2355 }
2356 int cf_item_is_pair(CONF_ITEM *item)
2357 {
2358         return item->type == CONF_ITEM_PAIR;
2359 }
2360
2361
2362 static CONF_DATA *cf_data_alloc(CONF_SECTION *parent, const char *name,
2363                                 void *data, void (*data_free)(void *))
2364 {
2365         char *p;
2366         size_t name_len;
2367         CONF_DATA *cd;
2368
2369         name_len = strlen(name) + 1;
2370
2371         p = rad_malloc(sizeof(*cd) + name_len);
2372         cd = (CONF_DATA *) p;
2373         memset(cd, 0, sizeof(*cd));
2374
2375         cd->item.type = CONF_ITEM_DATA;
2376         cd->item.parent = parent;
2377         cd->data = data;
2378         cd->free = data_free;
2379
2380         p += sizeof(*cd);
2381         memcpy(p, name, name_len);
2382         cd->name = p;
2383         return cd;
2384 }
2385
2386
2387 static void *cf_data_find_internal(CONF_SECTION *cs, const char *name,
2388                                    int flag)
2389 {
2390         if (!cs || !name) return NULL;
2391
2392         /*
2393          *      Find the name in the tree, for speed.
2394          */
2395         if (cs->data_tree) {
2396                 CONF_DATA mycd;
2397
2398                 mycd.name = name;
2399                 mycd.flag = flag;
2400                 return rbtree_finddata(cs->data_tree, &mycd);
2401         }
2402
2403         return NULL;
2404 }
2405
2406 /*
2407  *      Find data from a particular section.
2408  */
2409 void *cf_data_find(CONF_SECTION *cs, const char *name)
2410 {
2411         CONF_DATA *cd = cf_data_find_internal(cs, name, 0);
2412
2413         if (cd) return cd->data;
2414         return NULL;
2415 }
2416
2417
2418 /*
2419  *      Add named data to a configuration section.
2420  */
2421 static int cf_data_add_internal(CONF_SECTION *cs, const char *name,
2422                                 void *data, void (*data_free)(void *),
2423                                 int flag)
2424 {
2425         CONF_DATA *cd;
2426
2427         if (!cs || !name) return -1;
2428
2429         /*
2430          *      Already exists.  Can't add it.
2431          */
2432         if (cf_data_find_internal(cs, name, flag) != NULL) return -1;
2433
2434         cd = cf_data_alloc(cs, name, data, data_free);
2435         if (!cd) return -1;
2436         cd->flag = flag;
2437
2438         cf_item_add(cs, cf_datatoitem(cd));
2439
2440         return 0;
2441 }
2442
2443 /*
2444  *      Add named data to a configuration section.
2445  */
2446 int cf_data_add(CONF_SECTION *cs, const char *name,
2447                 void *data, void (*data_free)(void *))
2448 {
2449         return cf_data_add_internal(cs, name, data, data_free, 0);
2450 }
2451
2452 #if 0
2453 /*
2454  *      Copy CONF_DATA from src to dst
2455  */
2456 static void cf_section_copy_data(CONF_SECTION *s, CONF_SECTION *d)
2457 {
2458
2459         CONF_ITEM *cd, *next, **last;
2460
2461         /*
2462          *      Don't check if s->data_tree is NULL.  It's child
2463          *      sections may have data, even if this section doesn't.
2464          */
2465
2466         rad_assert(d->data_tree == NULL);
2467         d->data_tree = s->data_tree;
2468         s->data_tree = NULL;
2469
2470         /*
2471          *      Walk through src, moving CONF_ITEM_DATA
2472          *      to dst, by hand.
2473          */
2474         last = &(s->children);
2475         for (cd = s->children; cd != NULL; cd = next) {
2476                 next = cd->next;
2477
2478                 /*
2479                  *      Recursively copy data from child sections.
2480                  */
2481                 if (cd->type == CONF_ITEM_SECTION) {
2482                         CONF_SECTION *s1, *d1;
2483
2484                         s1 = cf_itemtosection(cd);
2485                         d1 = cf_section_sub_find_name2(d, s1->name1, s1->name2);
2486                         if (d1) {
2487                                 cf_section_copy_data(s1, d1);
2488                         }
2489                         last = &(cd->next);
2490                         continue;
2491                 }
2492
2493                 /*
2494                  *      Not conf data, remember last ptr.
2495                  */
2496                 if (cd->type != CONF_ITEM_DATA) {
2497                         last = &(cd->next);
2498                         continue;
2499                 }
2500
2501                 /*
2502                  *      Remove it from the src list
2503                  */
2504                 *last = cd->next;
2505                 cd->next = NULL;
2506
2507                 /*
2508                  *      Add it to the dst list
2509                  */
2510                 if (!d->children) {
2511                         rad_assert(d->tail == NULL);
2512                         d->children = cd;
2513                 } else {
2514                         rad_assert(d->tail != NULL);
2515                         d->tail->next = cd;
2516                 }
2517                 d->tail = cd;
2518         }
2519 }
2520
2521 /*
2522  *      For a CONF_DATA element, stat the filename, if necessary.
2523  */
2524 static int filename_stat(void *context, void *data)
2525 {
2526         struct stat buf;
2527         CONF_DATA *cd = data;
2528
2529         context = context;      /* -Wunused */
2530
2531         if (cd->flag != PW_TYPE_FILENAME) return 0;
2532
2533         if (stat(cd->name, &buf) < 0) return -1;
2534
2535         if (buf.st_mtime != *(time_t *) cd->data) return -1;
2536
2537         return 0;
2538 }
2539
2540
2541 /*
2542  *      Compare two CONF_SECTIONS.  The items MUST be in the same
2543  *      order.
2544  */
2545 static int cf_section_cmp(CONF_SECTION *a, CONF_SECTION *b)
2546 {
2547         CONF_ITEM *ca = a->children;
2548         CONF_ITEM *cb = b->children;
2549
2550         while (1) {
2551                 CONF_PAIR *pa, *pb;
2552
2553                 /*
2554                  *      Done.  Stop.
2555                  */
2556                 if (!ca && !cb) break;
2557
2558                 /*
2559                  *      Skip CONF_DATA.
2560                  */
2561                 if (ca && ca->type == CONF_ITEM_DATA) {
2562                         ca = ca->next;
2563                         continue;
2564                 }
2565                 if (cb && cb->type == CONF_ITEM_DATA) {
2566                         cb = cb->next;
2567                         continue;
2568                 }
2569
2570                 /*
2571                  *      One is smaller than the other.  Exit.
2572                  */
2573                 if (!ca || !cb) return 0;
2574
2575                 if (ca->type != cb->type) return 0;
2576
2577                 /*
2578                  *      Deal with subsections.
2579                  */
2580                 if (ca->type == CONF_ITEM_SECTION) {
2581                         CONF_SECTION *sa = cf_itemtosection(ca);
2582                         CONF_SECTION *sb = cf_itemtosection(cb);
2583
2584                         if (!cf_section_cmp(sa, sb)) return 0;
2585                         goto next;
2586                 }
2587
2588                 rad_assert(ca->type == CONF_ITEM_PAIR);
2589
2590                 pa = cf_itemtopair(ca);
2591                 pb = cf_itemtopair(cb);
2592
2593                 /*
2594                  *      Different attr and/or value, Exit.
2595                  */
2596                 if ((strcmp(pa->attr, pb->attr) != 0) ||
2597                     (strcmp(pa->value, pb->value) != 0)) return 0;
2598
2599
2600                 /*
2601                  *      And go to the next element.
2602                  */
2603         next:
2604                 ca = ca->next;
2605                 cb = cb->next;
2606         }
2607
2608         /*
2609          *      Walk over the CONF_DATA, stat'ing PW_TYPE_FILENAME.
2610          */
2611         if (a->data_tree &&
2612             (rbtree_walk(a->data_tree, InOrder, filename_stat, NULL) != 0)) {
2613                 return 0;
2614         }
2615
2616         /*
2617          *      They must be the same, say so.
2618          */
2619         return 1;
2620 }
2621
2622
2623 /*
2624  *      Migrate CONF_DATA from one section to another.
2625  */
2626 int cf_section_migrate(CONF_SECTION *dst, CONF_SECTION *src)
2627 {
2628         CONF_ITEM *ci;
2629         CONF_SECTION *s, *d;
2630
2631         for (ci = src->children; ci != NULL; ci = ci->next) {
2632                 if (ci->type != CONF_ITEM_SECTION)
2633                         continue;
2634
2635                 s = cf_itemtosection(ci);
2636                 d = cf_section_sub_find_name2(dst, s->name1, s->name2);
2637
2638                 if (!d) continue; /* not in new one, don't migrate it */
2639
2640                 /*
2641                  *      A section of the same name is in BOTH src & dst,
2642                  *      compare the CONF_PAIR's.  If they're all the same,
2643                  *      then copy the CONF_DATA from one to the other.
2644                  */
2645                 if (cf_section_cmp(s, d)) {
2646                         cf_section_copy_data(s, d);
2647                 }
2648         }
2649
2650         return 1;               /* rcode means anything? */
2651 }
2652 #endif
2653
2654 int cf_section_template(CONF_SECTION *cs, CONF_SECTION *template)
2655 {
2656         if (!cs || !template || cs->template || template->template) return -1;
2657
2658         cs->template = template;
2659
2660         return 0;
2661 }
2662
2663
2664 /*
2665  *      This is here to make the rest of the code easier to read.  It
2666  *      ties conffile.c to log.c, but it means we don't have to
2667  *      pollute every other function with the knowledge of the
2668  *      configuration internals.
2669  */
2670 void cf_log_err(CONF_ITEM *ci, const char *fmt, ...)
2671 {
2672         va_list ap;
2673         char buffer[256];
2674
2675         va_start(ap, fmt);
2676         vsnprintf(buffer, sizeof(buffer), fmt, ap);
2677         va_end(ap);
2678
2679         radlog(L_ERR, "%s[%d]: %s", ci->filename, ci->lineno, buffer);
2680 }
2681
2682
2683 void cf_log_info(CONF_SECTION *cs, const char *fmt, ...)
2684 {
2685         va_list ap;
2686
2687         va_start(ap, fmt);
2688         if (debug_flag > 1 && cf_log_config && cs) vradlog(L_DBG, fmt, ap);
2689         va_end(ap);
2690 }
2691
2692 /*
2693  *      Wrapper to simplify the code.
2694  */
2695 void cf_log_module(CONF_SECTION *cs, const char *fmt, ...)
2696 {
2697         va_list ap;
2698         char buffer[256];
2699
2700         va_start(ap, fmt);
2701         if (debug_flag > 1 && cf_log_modules && cs) {
2702                 vsnprintf(buffer, sizeof(buffer), fmt, ap);
2703
2704                 radlog(L_DBG, " Module: %s", buffer);
2705         }
2706         va_end(ap);
2707 }
2708
2709 const CONF_PARSER *cf_section_parse_table(CONF_SECTION *cs)
2710 {
2711         if (!cs) return NULL;
2712
2713         return cs->variables;
2714 }
2715
2716 #if 0
2717 /*
2718  * JMG dump_config tries to dump the config structure in a readable format
2719  *
2720 */
2721
2722 static int dump_config_section(CONF_SECTION *cs, int indent)
2723 {
2724         CONF_SECTION    *scs;
2725         CONF_PAIR       *cp;
2726         CONF_ITEM       *ci;
2727
2728         /* The DEBUG macro doesn't let me
2729          *   for(i=0;i<indent;++i) debugputchar('\t');
2730          * so I had to get creative. --Pac. */
2731
2732         for (ci = cs->children; ci; ci = ci->next) {
2733                 switch (ci->type) {
2734                 case CONF_ITEM_PAIR:
2735                         cp=cf_itemtopair(ci);
2736                         DEBUG("%.*s%s = %s",
2737                                 indent, "\t\t\t\t\t\t\t\t\t\t\t",
2738                                 cp->attr, cp->value);
2739                         break;
2740
2741                 case CONF_ITEM_SECTION:
2742                         scs=cf_itemtosection(ci);
2743                         DEBUG("%.*s%s %s%s{",
2744                                 indent, "\t\t\t\t\t\t\t\t\t\t\t",
2745                                 scs->name1,
2746                                 scs->name2 ? scs->name2 : "",
2747                                 scs->name2 ?  " " : "");
2748                         dump_config_section(scs, indent+1);
2749                         DEBUG("%.*s}",
2750                                 indent, "\t\t\t\t\t\t\t\t\t\t\t");
2751                         break;
2752
2753                 default:        /* FIXME: Do more! */
2754                         break;
2755                 }
2756         }
2757
2758         return 0;
2759 }
2760
2761 int dump_config(CONF_SECTION *cs)
2762 {
2763         return dump_config_section(cs, 0);
2764 }
2765 #endif
2766
2767 static const char *cf_pair_print_value(const CONF_PAIR *cp,
2768                                        char *buffer, size_t buflen)
2769 {
2770         char *p;
2771
2772         if (!cp->value) return "";
2773
2774         switch (cp->value_type) {
2775         default:
2776         case T_BARE_WORD:
2777                 snprintf(buffer, buflen, "%s", cp->value);
2778                 break;
2779
2780         case T_SINGLE_QUOTED_STRING:
2781                 snprintf(buffer, buflen, "'%s'", cp->value);
2782                 break;
2783
2784         case T_DOUBLE_QUOTED_STRING:
2785                 buffer[0] = '"';
2786                 fr_print_string(cp->value, strlen(cp->value),
2787                                 buffer + 1, buflen - 3);
2788                 p = buffer + strlen(buffer); /* yuck... */
2789                 p[0] = '"';
2790                 p[1] = '\0';
2791                 break;
2792         }
2793
2794         return buffer;
2795 }
2796
2797
2798 int cf_pair2xml(FILE *fp, const CONF_PAIR *cp)
2799 {
2800         fprintf(fp, "<%s>", cp->attr);
2801         if (cp->value) {
2802                 char buffer[2048];
2803
2804                 char *p = buffer;
2805                 const char *q = cp->value;
2806
2807                 while (*q && (p < (buffer + sizeof(buffer) - 1))) {
2808                         if (q[0] == '&') {
2809                                 memcpy(p, "&amp;", 4);
2810                                 p += 5;
2811
2812                         } else if (q[0] == '<') {
2813                                 memcpy(p, "&lt;", 4);
2814                                 p += 4;
2815
2816                         } else if (q[0] == '>') {
2817                                 memcpy(p, "&gt;", 4);
2818                                 p += 4;
2819
2820                         } else {
2821                                 *(p++) = *q;
2822                         }
2823                         q++;
2824                 }
2825
2826                 *p = '\0';
2827                 fprintf(fp, "%s", buffer);
2828         }
2829
2830         fprintf(fp, "</%s>\n", cp->attr);
2831
2832         return 1;
2833 }
2834
2835 int cf_section2xml(FILE *fp, const CONF_SECTION *cs)
2836 {
2837         CONF_ITEM *ci, *next;
2838
2839         /*
2840          *      Section header
2841          */
2842         fprintf(fp, "<%s>\n", cs->name1);
2843         if (cs->name2) {
2844                 fprintf(fp, "<_name2>%s</_name2>\n", cs->name2);
2845         }
2846
2847         /*
2848          *      Loop over contents.
2849          */
2850         for (ci = cs->children; ci; ci = next) {
2851                 next = ci->next;
2852
2853                 switch (ci->type) {
2854                 case CONF_ITEM_PAIR:
2855                         if (!cf_pair2xml(fp, (CONF_PAIR *) ci)) return 0;
2856                         break;
2857
2858                 case CONF_ITEM_SECTION:
2859                         if (!cf_section2xml(fp, (CONF_SECTION *) ci)) return 0;
2860                         break;
2861
2862                 default:        /* should really be an error. */
2863                         break;
2864                 
2865                 }
2866         }
2867
2868         fprintf(fp, "</%s>\n", cs->name1);
2869
2870         return 1;               /* success */
2871 }
2872
2873 int cf_pair2file(FILE *fp, const CONF_PAIR *cp)
2874 {
2875         char buffer[2048];
2876
2877         fprintf(fp, "\t%s = %s\n", cp->attr,
2878                 cf_pair_print_value(cp, buffer, sizeof(buffer)));
2879
2880         return 1;
2881 }
2882
2883 int cf_section2file(FILE *fp, const CONF_SECTION *cs)
2884 {
2885         const CONF_ITEM *ci, *next;
2886
2887         /*
2888          *      Section header
2889          */
2890         if (!cs->name2) {
2891                 fprintf(fp, "%s {\n", cs->name1);
2892         } else {
2893                 fprintf(fp, "%s %s {\n",
2894                         cs->name1, cs->name2);
2895         }
2896
2897         /*
2898          *      Loop over contents.
2899          */
2900         for (ci = cs->children; ci; ci = next) {
2901                 next = ci->next;
2902
2903                 switch (ci->type) {
2904                 case CONF_ITEM_PAIR:
2905                         if (!cf_pair2file(fp, (const CONF_PAIR *) ci)) return 0;
2906                         break;
2907
2908                 case CONF_ITEM_SECTION:
2909                         if (!cf_section2file(fp, (const CONF_SECTION *) ci)) return 0;
2910                         break;
2911
2912                 default:        /* should really be an error. */
2913                         break;
2914                 
2915                 }
2916         }
2917
2918         fprintf(fp, "}\n");
2919
2920         return 1;               /* success */
2921 }