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