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