Remove cf_template_copy and replace with cf_section_dup
[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 RCSID("$Id$")
30
31 #include <freeradius-devel/radiusd.h>
32 #include <freeradius-devel/parser.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_property {
46         CONF_PROPERTY_INVALID = 0,
47         CONF_PROPERTY_NAME,
48         CONF_PROPERTY_INSTANCE,
49 } CONF_PROPERTY;
50
51 static const FR_NAME_NUMBER conf_property_name[] = {
52         { "name",       CONF_PROPERTY_NAME},
53         { "instance",   CONF_PROPERTY_INSTANCE},
54
55         {  NULL , -1 }
56 };
57
58 typedef enum conf_type {
59         CONF_ITEM_INVALID = 0,
60         CONF_ITEM_PAIR,
61         CONF_ITEM_SECTION,
62         CONF_ITEM_DATA
63 } CONF_ITEM_TYPE;
64
65 struct conf_item {
66         struct conf_item *next;         //!< Sibling.
67         struct conf_part *parent;       //!< Parent.
68         int lineno;                     //!< The line number the config item began on.
69         char const *filename;           //!< The file the config item was parsed from.
70         CONF_ITEM_TYPE type;            //!< Whether the config item is a config_pair, conf_section or conf_data.
71 };
72
73 /** Configuration AVP similar to a VALUE_PAIR
74  *
75  */
76 struct conf_pair {
77         CONF_ITEM item;
78         char const *attr;               //!< Attribute name
79         char const *value;              //!< Attribute value
80         FR_TOKEN op;                    //!< Operator e.g. =, :=
81         FR_TOKEN value_type;            //!< Quoting style T_(DOUBLE|SINGLE|BACK)_QUOTE_STRING or T_BARE_WORD.
82 };
83
84 /** Internal data that is associated with a configuration section
85  *
86  */
87 struct conf_data {
88         CONF_ITEM  item;
89         char const *name;
90         int        flag;
91         void       *data;               //!< User data
92         void       (*free)(void *);     //!< Free user data function
93 };
94
95 struct conf_part {
96         CONF_ITEM item;
97         char const      *name1;
98         char const      *name2;
99         FR_TOKEN        name2_type;
100
101         CONF_ITEM       *children;
102         CONF_ITEM       *tail;          //!< For speed.
103         CONF_SECTION    *template;
104
105         rbtree_t        *pair_tree;     //!< and a partridge..
106         rbtree_t        *section_tree;  //!< no jokes here.
107         rbtree_t        *name2_tree;    //!< for sections of the same name2
108         rbtree_t        *data_tree;
109
110         void            *base;
111         int             depth;
112
113         CONF_PARSER const *variables;
114 };
115
116 CONF_SECTION *root_config = NULL;
117 bool cf_new_escape = false;
118
119
120 static int              cf_data_add_internal(CONF_SECTION *cs, char const *name, void *data,
121                                              void (*data_free)(void *), int flag);
122
123 static void             *cf_data_find_internal(CONF_SECTION const *cs, char const *name, int flag);
124
125 static char const       *cf_expand_variables(char const *cf, int *lineno,
126                                              CONF_SECTION *outercs,
127                                              char *output, size_t outsize,
128                                              char const *input);
129
130 /*
131  *      Isolate the scary casts in these tiny provably-safe functions
132  */
133
134 /** Cast a CONF_ITEM to a CONF_PAIR
135  *
136  */
137 CONF_PAIR *cf_item_to_pair(CONF_ITEM const *ci)
138 {
139         CONF_PAIR *out;
140
141         if (ci == NULL) return NULL;
142
143         rad_assert(ci->type == CONF_ITEM_PAIR);
144
145         memcpy(&out, &ci, sizeof(out));
146         return out;
147 }
148
149 /** Cast a CONF_ITEM to a CONF_SECTION
150  *
151  */
152 CONF_SECTION *cf_item_to_section(CONF_ITEM const *ci)
153 {
154         CONF_SECTION *out;
155
156         if (ci == NULL) return NULL;
157
158         rad_assert(ci->type == CONF_ITEM_SECTION);
159
160         memcpy(&out, &ci, sizeof(out));
161         return out;
162 }
163
164 /** Cast a CONF_PAIR to a CONF_ITEM
165  *
166  */
167 CONF_ITEM *cf_pair_to_item(CONF_PAIR const *cp)
168 {
169         CONF_ITEM *out;
170
171         if (cp == NULL) return NULL;
172
173         memcpy(&out, &cp, sizeof(out));
174         return out;
175 }
176
177 /** Cast a CONF_SECTION to a CONF_ITEM
178  *
179  */
180 CONF_ITEM *cf_section_to_item(CONF_SECTION const *cs)
181 {
182         CONF_ITEM *out;
183
184         if (cs == NULL) return NULL;
185
186         memcpy(&out, &cs, sizeof(out));
187         return out;
188 }
189
190 /** Cast CONF_DATA to a CONF_ITEM
191  *
192  */
193 static CONF_ITEM *cf_data_to_item(CONF_DATA const *cd)
194 {
195         CONF_ITEM *out;
196
197         if (cd == NULL) {
198                 return NULL;
199         }
200
201         memcpy(&out, &cd, sizeof(out));
202         return out;
203 }
204
205 static int _cf_data_free(CONF_DATA *cd)
206 {
207         if (cd->free) cd->free(cd->data);
208
209         return 0;
210 }
211
212 /*
213  *      rbtree callback function
214  */
215 static int pair_cmp(void const *a, void const *b)
216 {
217         CONF_PAIR const *one = a;
218         CONF_PAIR const *two = b;
219
220         return strcmp(one->attr, two->attr);
221 }
222
223
224 /*
225  *      rbtree callback function
226  */
227 static int section_cmp(void const *a, void const *b)
228 {
229         CONF_SECTION const *one = a;
230         CONF_SECTION const *two = b;
231
232         return strcmp(one->name1, two->name1);
233 }
234
235
236 /*
237  *      rbtree callback function
238  */
239 static int name2_cmp(void const *a, void const *b)
240 {
241         CONF_SECTION const *one = a;
242         CONF_SECTION const *two = b;
243
244         rad_assert(strcmp(one->name1, two->name1) == 0);
245
246         if (!one->name2 && !two->name2) return 0;
247         if (one->name2 && !two->name2) return -1;
248         if (!one->name2 && two->name2) return +1;
249
250         return strcmp(one->name2, two->name2);
251 }
252
253
254 /*
255  *      rbtree callback function
256  */
257 static int data_cmp(void const *a, void const *b)
258 {
259         int rcode;
260
261         CONF_DATA const *one = a;
262         CONF_DATA const *two = b;
263
264         rcode = one->flag - two->flag;
265         if (rcode != 0) return rcode;
266
267         return strcmp(one->name, two->name);
268 }
269
270 static int _cf_section_free(CONF_SECTION *cs)
271 {
272         /*
273          *      Name1 and name2 are allocated contiguous with
274          *      cs.
275          */
276         if (cs->pair_tree) {
277                 rbtree_free(cs->pair_tree);
278                 cs->pair_tree = NULL;
279         }
280         if (cs->section_tree) {
281                 rbtree_free(cs->section_tree);
282                 cs->section_tree = NULL;
283         }
284         if (cs->name2_tree) {
285                 rbtree_free(cs->name2_tree);
286                 cs->name2_tree = NULL;
287         }
288         if (cs->data_tree) {
289                 rbtree_free(cs->data_tree);
290                 cs->data_tree = NULL;
291         }
292
293         return 0;
294 }
295
296 /** Allocate a CONF_PAIR
297  *
298  * @param parent CONF_SECTION to hang this CONF_PAIR off of.
299  * @param attr name.
300  * @param value of CONF_PAIR.
301  * @param op T_OP_EQ, T_OP_SET etc.
302  * @param value_type T_BARE_WORD, T_DOUBLE_QUOTED_STRING, T_BACK_QUOTED_STRING
303  * @return NULL on error, else a new CONF_SECTION parented by parent.
304  */
305 CONF_PAIR *cf_pair_alloc(CONF_SECTION *parent, char const *attr, char const *value,
306                          FR_TOKEN op, FR_TOKEN value_type)
307 {
308         CONF_PAIR *cp;
309
310         if (!attr) return NULL;
311
312         cp = talloc_zero(parent, CONF_PAIR);
313         if (!cp) return NULL;
314
315         cp->item.type = CONF_ITEM_PAIR;
316         cp->item.parent = parent;
317         cp->value_type = value_type;
318         cp->op = op;
319
320         cp->attr = talloc_typed_strdup(cp, attr);
321         if (!cp->attr) {
322         error:
323                 talloc_free(cp);
324                 return NULL;
325         }
326
327         if (value) {
328                 cp->value = talloc_typed_strdup(cp, value);
329                 if (!cp->value) goto error;
330         }
331
332         return cp;
333 }
334
335 /** Duplicate a CONF_PAIR
336  *
337  * @param parent to allocate new pair in.
338  * @param cp to duplicate.
339  * @return NULL on error, else a duplicate of the input pair.
340  */
341 CONF_PAIR *cf_pair_dup(CONF_SECTION *parent, CONF_PAIR *cp)
342 {
343         CONF_PAIR *new;
344
345         rad_assert(parent);
346         rad_assert(cp);
347
348         new = cf_pair_alloc(parent, cf_pair_attr(cp), cf_pair_value(cp), cf_pair_operator(cp), cf_pair_value_type(cp));
349         if (new) {
350                 new->item.lineno = cp->item.lineno;
351                 new->item.filename = talloc_strdup(new, cp->item.filename);
352         }
353
354         return new;
355 }
356
357 /** Add a configuration pair to a section
358  *
359  * @param parent section to add pair to.
360  * @param cp to add.
361  */
362 void cf_pair_add(CONF_SECTION *parent, CONF_PAIR *cp)
363 {
364         cf_item_add(parent, cf_pair_to_item(cp));
365 }
366
367 /** Allocate a CONF_SECTION
368  *
369  * @param parent CONF_SECTION to hang this CONF_SECTION off of.
370  * @param name1 Primary name.
371  * @param name2 Secondary name.
372  * @return NULL on error, else a new CONF_SECTION parented by parent.
373  */
374 CONF_SECTION *cf_section_alloc(CONF_SECTION *parent, char const *name1, char const *name2)
375 {
376         CONF_SECTION *cs;
377         char buffer[1024];
378
379         if (!name1) return NULL;
380
381         if (name2) {
382                 if (strchr(name2, '$')) {
383                         name2 = cf_expand_variables(parent->item.filename,
384                                                 &parent->item.lineno,
385                                                 parent,
386                                                 buffer, sizeof(buffer), name2);
387                         if (!name2) {
388                                 ERROR("Failed expanding section name");
389                                 return NULL;
390                         }
391                 }
392         }
393
394         cs = talloc_zero(parent, CONF_SECTION);
395         if (!cs) return NULL;
396
397         cs->item.type = CONF_ITEM_SECTION;
398         cs->item.parent = parent;
399
400         cs->name1 = talloc_typed_strdup(cs, name1);
401         if (!cs->name1) {
402         error:
403                 talloc_free(cs);
404                 return NULL;
405         }
406
407         if (name2) {
408                 cs->name2 = talloc_typed_strdup(cs, name2);
409                 if (!cs->name2) goto error;
410         }
411
412         cs->pair_tree = rbtree_create(cs, pair_cmp, NULL, 0);
413         if (!cs->pair_tree) goto error;
414
415         talloc_set_destructor(cs, _cf_section_free);
416
417         /*
418          *      Don't create a data tree, it may not be needed.
419          */
420
421         /*
422          *      Don't create the section tree here, it may not
423          *      be needed.
424          */
425
426         if (parent) cs->depth = parent->depth + 1;
427
428         return cs;
429 }
430
431 /** Duplicate a configuration section
432  *
433  * @note recursively duplicates any child sections.
434  * @note does not duplicate any data associated with a section, or its child sections.
435  *
436  * @param parent section.
437  * @param cs to duplicate.
438  * @param name1 of new section.
439  * @param name2 of new section.
440  * @param copy_meta Copy additional meta data for a section (like template, base, depth and variables).
441  * @return a duplicate of the existing section, or NULL on error.
442  */
443 CONF_SECTION *cf_section_dup(CONF_SECTION *parent, CONF_SECTION const *cs,
444                              char const *name1, char const *name2, bool copy_meta)
445 {
446         CONF_SECTION *new, *subcs;
447         CONF_PAIR *cp;
448         CONF_ITEM *ci;
449
450         new = cf_section_alloc(parent, name1, name2);
451
452         if (copy_meta) {
453                 new->template = cs->template;
454                 new->base = cs->base;
455                 new->depth = cs->depth;
456                 new->variables = cs->variables;
457         }
458
459         new->item.lineno = cs->item.lineno;
460         new->item.filename = talloc_strdup(new, cs->item.filename);
461
462         for (ci = cs->children; ci; ci = ci->next) {
463                 switch (ci->type) {
464                 case CONF_ITEM_SECTION:
465                         subcs = cf_item_to_section(ci);
466                         subcs = cf_section_dup(new, subcs,
467                                                cf_section_name1(subcs), cf_section_name2(subcs),
468                                                copy_meta);
469                         if (!subcs) {
470                                 talloc_free(new);
471                                 return NULL;
472                         }
473                         cf_section_add(new, subcs);
474                         break;
475
476                 case CONF_ITEM_PAIR:
477                         cp = cf_pair_dup(new, cf_item_to_pair(ci));
478                         if (!cp) {
479                                 talloc_free(new);
480                                 return NULL;
481                         }
482                         cf_pair_add(new, cp);
483                         break;
484
485                 case CONF_ITEM_DATA: /* Skip data */
486                         break;
487
488                 case CONF_ITEM_INVALID:
489                         rad_assert(0);
490                 }
491         }
492
493         return new;
494 }
495
496 void cf_section_add(CONF_SECTION *parent, CONF_SECTION *cs)
497 {
498         cf_item_add(parent, &(cs->item));
499 }
500
501 /*
502  *      Replace pair in a given section with a new pair,
503  *      of the given value.
504  */
505 int cf_pair_replace(CONF_SECTION *cs, CONF_PAIR *cp, char const *value)
506 {
507         CONF_PAIR *newp;
508         CONF_ITEM *ci, *cn, **last;
509
510         newp = cf_pair_alloc(cs, cp->attr, value, cp->op, cp->value_type);
511         if (!newp) return -1;
512
513         ci = &(cp->item);
514         cn = &(newp->item);
515
516         /*
517          *      Find the old one from the linked list, and replace it
518          *      with the new one.
519          */
520         for (last = &cs->children; (*last) != NULL; last = &(*last)->next) {
521                 if (*last == ci) {
522                         cn->next = (*last)->next;
523                         *last = cn;
524                         ci->next = NULL;
525                         break;
526                 }
527         }
528
529         rbtree_deletebydata(cs->pair_tree, ci);
530
531         rbtree_insert(cs->pair_tree, cn);
532
533         return 0;
534 }
535
536
537 /*
538  *      Add an item to a configuration section.
539  */
540 void cf_item_add(CONF_SECTION *cs, CONF_ITEM *ci)
541 {
542         CONF_ITEM *first = ci;
543
544         rad_assert((void *)cs != (void *)ci);
545
546         if (!cs || !ci) return;
547
548         if (!cs->children) {
549                 rad_assert(cs->tail == NULL);
550                 cs->children = ci;
551         } else {
552                 rad_assert(cs->tail != NULL);
553                 cs->tail->next = ci;
554         }
555
556         /*
557          *      Update the trees (and tail) for each item added.
558          */
559         for (/* nothing */; ci != NULL; ci = ci->next) {
560                 rad_assert(ci->next != first);  /* simple cycle detection */
561
562                 cs->tail = ci;
563
564                 /*
565                  *      For fast lookups, pairs and sections get
566                  *      added to rbtree's.
567                  */
568                 switch (ci->type) {
569                 case CONF_ITEM_PAIR:
570                         if (!rbtree_insert(cs->pair_tree, ci)) {
571                                 CONF_PAIR *cp = cf_item_to_pair(ci);
572
573                                 if (strcmp(cp->attr, "confdir") == 0) break;
574                                 if (!cp->value) break; /* module name, "ok", etc. */
575                         }
576                         break;
577
578                 case CONF_ITEM_SECTION: {
579                         CONF_SECTION *cs_new = cf_item_to_section(ci);
580                         CONF_SECTION *name1_cs;
581
582                         if (!cs->section_tree) {
583                                 cs->section_tree = rbtree_create(cs, section_cmp, NULL, 0);
584                                 if (!cs->section_tree) {
585                                         ERROR("Out of memory");
586                                         fr_exit_now(1);
587                                 }
588                         }
589
590                         name1_cs = rbtree_finddata(cs->section_tree, cs_new);
591                         if (!name1_cs) {
592                                 if (!rbtree_insert(cs->section_tree, cs_new)) {
593                                         ERROR("Failed inserting section into tree");
594                                         fr_exit_now(1);
595                                 }
596                                 break;
597                         }
598
599                         /*
600                          *      We already have a section of
601                          *      this "name1".  Add a new
602                          *      sub-section based on name2.
603                          */
604                         if (!name1_cs->name2_tree) {
605                                 name1_cs->name2_tree = rbtree_create(name1_cs, name2_cmp, NULL, 0);
606                                 if (!name1_cs->name2_tree) {
607                                         ERROR("Out of memory");
608                                         fr_exit_now(1);
609                                 }
610                         }
611
612                         /*
613                          *      We don't care if this fails.
614                          *      If the user tries to create
615                          *      two sections of the same
616                          *      name1/name2, the duplicate
617                          *      section is just silently
618                          *      ignored.
619                          */
620                         rbtree_insert(name1_cs->name2_tree, cs_new);
621                         break;
622                 } /* was a section */
623
624                 case CONF_ITEM_DATA:
625                         if (!cs->data_tree) {
626                                 cs->data_tree = rbtree_create(cs, data_cmp, NULL, 0);
627                         }
628                         if (cs->data_tree) {
629                                 rbtree_insert(cs->data_tree, ci);
630                         }
631                         break;
632
633                 default: /* FIXME: assert & error! */
634                         break;
635
636                 } /* switch over conf types */
637         } /* loop over ci */
638 }
639
640
641 CONF_ITEM *cf_reference_item(CONF_SECTION const *parentcs,
642                              CONF_SECTION *outercs,
643                              char const *ptr)
644 {
645         CONF_PAIR *cp;
646         CONF_SECTION *next;
647         CONF_SECTION const *cs = outercs;
648         char name[8192];
649         char *p;
650
651         strlcpy(name, ptr, sizeof(name));
652         p = name;
653
654         /*
655          *      ".foo" means "foo from the current section"
656          */
657         if (*p == '.') {
658                 p++;
659
660                 /*
661                  *      Just '.' means the current section
662                  */
663                 if (*p == '\0') {
664                         return cf_section_to_item(cs);
665                 }
666
667                 /*
668                  *      ..foo means "foo from the section
669                  *      enclosing this section" (etc.)
670                  */
671                 while (*p == '.') {
672                         if (cs->item.parent) {
673                                 cs = cs->item.parent;
674                         }
675
676                         /*
677                          *      .. means the section
678                          *      enclosing this section
679                          */
680                         if (!*++p) {
681                                 return cf_section_to_item(cs);
682                         }
683                 }
684
685                 /*
686                  *      "foo.bar.baz" means "from the root"
687                  */
688         } else if (strchr(p, '.') != NULL) {
689                 if (!parentcs) goto no_such_item;
690
691                 cs = parentcs;
692         }
693
694         while (*p) {
695                 char *q, *r;
696
697                 r = strchr(p, '[');
698                 q = strchr(p, '.');
699                 if (!r && !q) break;
700
701                 if (r && q > r) q = NULL;
702                 if (q && q < r) r = NULL;
703
704                 /*
705                  *      Split off name2.
706                  */
707                 if (r) {
708                         q = strchr(r + 1, ']');
709                         if (!q) return NULL; /* parse error */
710
711                         /*
712                          *      Points to foo[bar]xx: parse error,
713                          *      it should be foo[bar] or foo[bar].baz
714                          */
715                         if (q[1] && q[1] != '.') goto no_such_item;
716
717                         *r = '\0';
718                         *q = '\0';
719                         next = cf_section_sub_find_name2(cs, p, r + 1);
720                         *r = '[';
721                         *q = ']';
722
723                         /*
724                          *      Points to a named instance of a section.
725                          */
726                         if (!q[1]) {
727                                 if (!next) goto no_such_item;
728                                 return &(next->item);
729                         }
730
731                         q++;    /* ensure we skip the ']' and '.' */
732
733                 } else {
734                         *q = '\0';
735                         next = cf_section_sub_find(cs, p);
736                         *q = '.';
737                 }
738
739                 if (!next) break; /* it MAY be a pair in this section! */
740
741                 cs = next;
742                 p = q + 1;
743         }
744
745         if (!*p) goto no_such_item;
746
747  retry:
748         /*
749          *      Find it in the current referenced
750          *      section.
751          */
752         cp = cf_pair_find(cs, p);
753         if (cp) return &(cp->item);
754
755         next = cf_section_sub_find(cs, p);
756         if (next) return &(next->item);
757
758         /*
759          *      "foo" is "in the current section, OR in main".
760          */
761         if ((p == name) && (parentcs != NULL) && (cs != parentcs)) {
762                 cs = parentcs;
763                 goto retry;
764         }
765
766 no_such_item:
767         WARN("No such configuration item %s", ptr);
768         return NULL;
769 }
770
771
772 CONF_SECTION *cf_top_section(CONF_SECTION *cs)
773 {
774         if (!cs) return NULL;
775
776         while (cs->item.parent != NULL) {
777                 cs = cs->item.parent;
778         }
779
780         return cs;
781 }
782
783
784 /*
785  *      Expand the variables in an input string.
786  */
787 static char const *cf_expand_variables(char const *cf, int *lineno,
788                                        CONF_SECTION *outercs,
789                                        char *output, size_t outsize,
790                                        char const *input)
791 {
792         char *p;
793         char const *end, *ptr;
794         CONF_SECTION const *parentcs;
795         char name[8192];
796
797         /*
798          *      Find the master parent conf section.
799          *      We can't use main_config.config, because we're in the
800          *      process of re-building it, and it isn't set up yet...
801          */
802         parentcs = cf_top_section(outercs);
803
804         p = output;
805         ptr = input;
806         while (*ptr) {
807                 /*
808                  *      Ignore anything other than "${"
809                  */
810                 if ((*ptr == '$') && (ptr[1] == '{')) {
811                         CONF_ITEM *ci;
812                         CONF_PAIR *cp;
813                         char *q;
814
815                         /*
816                          *      FIXME: Add support for ${foo:-bar},
817                          *      like in xlat.c
818                          */
819
820                         /*
821                          *      Look for trailing '}', and log a
822                          *      warning for anything that doesn't match,
823                          *      and exit with a fatal error.
824                          */
825                         end = strchr(ptr, '}');
826                         if (end == NULL) {
827                                 *p = '\0';
828                                 INFO("%s[%d]: Variable expansion missing }",
829                                        cf, *lineno);
830                                 return NULL;
831                         }
832
833                         ptr += 2;
834
835                         /*
836                          *      Can't really happen because input lines are
837                          *      capped at 8k, which is sizeof(name)
838                          */
839                         if ((size_t) (end - ptr) >= sizeof(name)) {
840                                 ERROR("%s[%d]: Reference string is too large",
841                                        cf, *lineno);
842                                 return NULL;
843                         }
844
845                         memcpy(name, ptr, end - ptr);
846                         name[end - ptr] = '\0';
847
848                         q = strchr(name, ':');
849                         if (q) {
850                                 *(q++) = '\0';
851                         }
852
853                         ci = cf_reference_item(parentcs, outercs, name);
854                         if (!ci) {
855                                 ERROR("%s[%d]: Reference \"%s\" not found", cf, *lineno, input);
856                                 return NULL;
857                         }
858
859                         /*
860                          *      The expansion doesn't refer to another item or section
861                          *      it's the property of a section.
862                          */
863                         if (q) {
864                                 CONF_SECTION *mycs = cf_item_to_section(ci);
865
866                                 if (ci->type != CONF_ITEM_SECTION) {
867                                         ERROR("%s[%d]: Can only reference properties of sections", cf, *lineno);
868                                         return NULL;
869                                 }
870
871                                 switch (fr_str2int(conf_property_name, q, CONF_PROPERTY_INVALID)) {
872                                 case CONF_PROPERTY_NAME:
873                                         strcpy(p, mycs->name1);
874                                         break;
875
876                                 case CONF_PROPERTY_INSTANCE:
877                                         strcpy(p, mycs->name2 ? mycs->name2 : mycs->name1);
878                                         break;
879
880                                 default:
881                                         ERROR("%s[%d]: Invalid property '%s'", cf, *lineno, q);
882                                         return NULL;
883                                 }
884                                 p += strlen(p);
885                                 ptr = end + 1;
886
887                         } else if (ci->type == CONF_ITEM_PAIR) {
888                                 /*
889                                  *  Substitute the value of the variable.
890                                  */
891                                 cp = cf_item_to_pair(ci);
892                                 if (!cp->value) {
893                                         ERROR("%s[%d]: Reference \"%s\" has no value",
894                                                cf, *lineno, input);
895                                         return NULL;
896                                 }
897
898                                 if (p + strlen(cp->value) >= output + outsize) {
899                                         ERROR("%s[%d]: Reference \"%s\" is too long",
900                                                cf, *lineno, input);
901                                         return NULL;
902                                 }
903
904                                 strcpy(p, cp->value);
905                                 p += strlen(p);
906                                 ptr = end + 1;
907
908                         } else if (ci->type == CONF_ITEM_SECTION) {
909                                 CONF_SECTION *subcs;
910
911                                 /*
912                                  *      Adding an entry again to a
913                                  *      section is wrong.  We don't
914                                  *      want an infinite loop.
915                                  */
916                                 if (ci->parent == outercs) {
917                                         ERROR("%s[%d]: Cannot reference different item in same section", cf, *lineno);
918                                         return NULL;
919                                 }
920
921                                 /*
922                                  *      Copy the section instead of
923                                  *      referencing it.
924                                  */
925                                 subcs = cf_item_to_section(ci);
926                                 subcs = cf_section_dup(outercs, subcs,
927                                                        cf_section_name1(subcs), cf_section_name2(subcs),
928                                                        false);
929                                 if (!subcs) {
930                                         ERROR("%s[%d]: Failed copying reference %s", cf, *lineno, name);
931                                         return NULL;
932                                 }
933
934                                 subcs->item.filename = ci->filename;
935                                 subcs->item.lineno = ci->lineno;
936                                 cf_item_add(outercs, &(subcs->item));
937
938                                 ptr = end + 1;
939
940                         } else {
941                                 ERROR("%s[%d]: Reference \"%s\" type is invalid", cf, *lineno, input);
942                                 return NULL;
943                         }
944                 } else if (memcmp(ptr, "$ENV{", 5) == 0) {
945                         char *env;
946
947                         ptr += 5;
948
949                         /*
950                          *      Look for trailing '}', and log a
951                          *      warning for anything that doesn't match,
952                          *      and exit with a fatal error.
953                          */
954                         end = strchr(ptr, '}');
955                         if (end == NULL) {
956                                 *p = '\0';
957                                 INFO("%s[%d]: Environment variable expansion missing }",
958                                        cf, *lineno);
959                                 return NULL;
960                         }
961
962                         /*
963                          *      Can't really happen because input lines are
964                          *      capped at 8k, which is sizeof(name)
965                          */
966                         if ((size_t) (end - ptr) >= sizeof(name)) {
967                                 ERROR("%s[%d]: Environment variable name is too large",
968                                        cf, *lineno);
969                                 return NULL;
970                         }
971
972                         memcpy(name, ptr, end - ptr);
973                         name[end - ptr] = '\0';
974
975                         /*
976                          *      Get the environment variable.
977                          *      If none exists, then make it an empty string.
978                          */
979                         env = getenv(name);
980                         if (env == NULL) {
981                                 *name = '\0';
982                                 env = name;
983                         }
984
985                         if (p + strlen(env) >= output + outsize) {
986                                 ERROR("%s[%d]: Reference \"%s\" is too long",
987                                        cf, *lineno, input);
988                                 return NULL;
989                         }
990
991                         strcpy(p, env);
992                         p += strlen(p);
993                         ptr = end + 1;
994
995                 } else {
996                         /*
997                          *      Copy it over verbatim.
998                          */
999                         *(p++) = *(ptr++);
1000                 }
1001
1002
1003                 if (p >= (output + outsize)) {
1004                         ERROR("%s[%d]: Reference \"%s\" is too long",
1005                                cf, *lineno, input);
1006                         return NULL;
1007                 }
1008         } /* loop over all of the input string. */
1009
1010         *p = '\0';
1011
1012         return output;
1013 }
1014
1015 static char const parse_spaces[] = "                                                                                                                                                                                                                                                                ";
1016
1017 /** Validation function for ipaddr conffile types
1018  *
1019  */
1020 static inline int fr_item_validate_ipaddr(CONF_SECTION *cs, char const *name, PW_TYPE type, char const *value,
1021                                           fr_ipaddr_t *ipaddr)
1022 {
1023         char ipbuf[128];
1024
1025         if (strcmp(value, "*") == 0) {
1026                 cf_log_info(cs, "%.*s\t%s = *", cs->depth, parse_spaces, name);
1027         } else if (strspn(value, ".0123456789abdefABCDEF:%[]/") == strlen(value)) {
1028                 cf_log_info(cs, "%.*s\t%s = %s", cs->depth, parse_spaces, name, value);
1029         } else {
1030                 cf_log_info(cs, "%.*s\t%s = %s IPv%s address [%s]", cs->depth, parse_spaces, name, value,
1031                             (ipaddr->af == AF_INET ? "4" : " 6"), ip_ntoh(ipaddr, ipbuf, sizeof(ipbuf)));
1032         }
1033
1034         switch (type) {
1035         case PW_TYPE_IPV4_ADDR:
1036         case PW_TYPE_IPV6_ADDR:
1037         case PW_TYPE_COMBO_IP_ADDR:
1038                 switch (ipaddr->af) {
1039                 case AF_INET:
1040                 if (ipaddr->prefix != 32) {
1041                         ERROR("Invalid IPv4 mask length \"/%i\".  Only \"/32\" permitted for non-prefix types",
1042                               ipaddr->prefix);
1043
1044                         return -1;
1045                 }
1046                         break;
1047
1048                 case AF_INET6:
1049                 if (ipaddr->prefix != 128) {
1050                         ERROR("Invalid IPv6 mask length \"/%i\".  Only \"/128\" permitted for non-prefix types",
1051                               ipaddr->prefix);
1052
1053                         return -1;
1054                 }
1055                         break;
1056
1057                 default:
1058                         return -1;
1059                 }
1060         default:
1061                 return 0;
1062         }
1063 }
1064
1065 /*
1066  *      Parses an item (not a CONF_ITEM) into the specified format,
1067  *      with a default value.
1068  *
1069  *      Returns -1 on error, -2 if deprecated, 0 for correctly parsed,
1070  *      and 1 if the default value was used.  Note that the default
1071  *      value will be used ONLY if the CONF_PAIR is NULL.
1072  */
1073 int cf_item_parse(CONF_SECTION *cs, char const *name, int type, void *data, char const *dflt)
1074 {
1075         int rcode;
1076         bool deprecated, required, attribute, secret, input, cant_be_empty;
1077         char **q;
1078         char const *value;
1079         CONF_PAIR const *cp = NULL;
1080         fr_ipaddr_t *ipaddr;
1081         char buffer[8192];
1082
1083         if (!cs) return -1;
1084
1085         deprecated = (type & PW_TYPE_DEPRECATED);
1086         required = (type & PW_TYPE_REQUIRED);
1087         attribute = (type & PW_TYPE_ATTRIBUTE);
1088         secret = (type & PW_TYPE_SECRET);
1089         input = (type == PW_TYPE_FILE_INPUT);   /* check, not and */
1090         cant_be_empty = (type & PW_TYPE_NOT_EMPTY);
1091
1092         if (attribute) required = true;
1093         if (required) cant_be_empty = true;     /* May want to review this in the future... */
1094
1095         type &= 0xff;                           /* normal types are small */
1096         rcode = 0;
1097
1098         cp = cf_pair_find(cs, name);
1099         if (cp) {
1100                 value = cp->value;
1101         } else {
1102                 rcode = 1;
1103                 value = dflt;
1104         }
1105
1106         if (!value) {
1107                 if (required) {
1108                 is_required:
1109                         if (!cp) {
1110                                 cf_log_err(&(cs->item), "Configuration item '%s' must have a value", name);
1111                         } else {
1112                                 cf_log_err(&(cp->item), "Configuration item '%s' must have a value", name);
1113                         }
1114                         return -1;
1115                 }
1116                 return rcode;
1117         }
1118
1119         if ((value[0] == '\0') && cant_be_empty) {
1120         cant_be_empty:
1121                 if (!cp) {
1122                         cf_log_err(&(cs->item), "Configuration item '%s' must not be empty (zero length)", name);
1123                         if (!required) cf_log_err(&(cs->item), "Comment item to silence this message");
1124                 } else {
1125                         cf_log_err(&(cp->item), "Configuration item '%s' must not be empty (zero length)", name);
1126                         if (!required) cf_log_err(&(cp->item), "Comment item to silence this message");
1127                 }
1128                 return -1;
1129         }
1130
1131         if (deprecated) {
1132                 cf_log_err(&(cs->item), "Configuration item \"%s\" is deprecated", name);
1133
1134                 return -2;
1135         }
1136
1137         switch (type) {
1138         case PW_TYPE_BOOLEAN:
1139                 /*
1140                  *      Allow yes/no and on/off
1141                  */
1142                 if ((strcasecmp(value, "yes") == 0) ||
1143                     (strcasecmp(value, "on") == 0)) {
1144                         *(bool *)data = true;
1145                 } else if ((strcasecmp(value, "no") == 0) ||
1146                            (strcasecmp(value, "off") == 0)) {
1147                         *(bool *)data = false;
1148                 } else {
1149                         *(bool *)data = false;
1150                         cf_log_err(&(cs->item), "Invalid value \"%s\" for boolean "
1151                                "variable %s", value, name);
1152                         return -1;
1153                 }
1154                 cf_log_info(cs, "%.*s\t%s = %s",
1155                             cs->depth, parse_spaces, name, value);
1156                 break;
1157
1158         case PW_TYPE_INTEGER:
1159         {
1160                 unsigned long v = strtoul(value, 0, 0);
1161
1162                 /*
1163                  *      Restrict integer values to 0-INT32_MAX, this means
1164                  *      it will always be safe to cast them to a signed type
1165                  *      for comparisons, and imposes the same range limit as
1166                  *      before we switched to using an unsigned type to
1167                  *      represent config item integers.
1168                  */
1169                 if (v > INT32_MAX) {
1170                         cf_log_err(&(cs->item), "Invalid value \"%s\" for variable %s, must be between 0-%u", value,
1171                                    name, INT32_MAX);
1172                         return -1;
1173                 }
1174
1175                 *(uint32_t *)data = v;
1176                 cf_log_info(cs, "%.*s\t%s = %u", cs->depth, parse_spaces, name, *(uint32_t *)data);
1177         }
1178                 break;
1179
1180         case PW_TYPE_SHORT:
1181         {
1182                 unsigned long v = strtoul(value, 0, 0);
1183
1184                 if (v > UINT16_MAX) {
1185                         cf_log_err(&(cs->item), "Invalid value \"%s\" for variable %s, must be between 0-%u", value,
1186                                    name, UINT16_MAX);
1187                         return -1;
1188                 }
1189                 *(uint16_t *)data = (uint16_t) v;
1190                 cf_log_info(cs, "%.*s\t%s = %u", cs->depth, parse_spaces, name, *(uint16_t *)data);
1191         }
1192                 break;
1193
1194         case PW_TYPE_INTEGER64:
1195                 *(uint64_t *)data = strtoull(value, 0, 0);
1196                 cf_log_info(cs, "%.*s\t%s = %" PRIu64, cs->depth, parse_spaces, name, *(uint64_t *)data);
1197                 break;
1198
1199         case PW_TYPE_SIGNED:
1200                 *(int32_t *)data = strtol(value, 0, 0);
1201                 cf_log_info(cs, "%.*s\t%s = %d", cs->depth, parse_spaces, name, *(int32_t *)data);
1202                 break;
1203
1204         case PW_TYPE_STRING:
1205                 q = (char **) data;
1206                 if (*q != NULL) {
1207                         talloc_free(*q);
1208                 }
1209
1210                 /*
1211                  *      Expand variables which haven't already been
1212                  *      expanded automagically when the configuration
1213                  *      file was read.
1214                  */
1215                 if (value == dflt) {
1216                         int lineno = 0;
1217
1218                         lineno = cs->item.lineno;
1219
1220                         value = cf_expand_variables("<internal>",
1221                                                     &lineno,
1222                                                     cs, buffer, sizeof(buffer),
1223                                                     value);
1224                         if (!value) {
1225                                 cf_log_err(&(cs->item),"Failed expanding variable %s", name);
1226                                 return -1;
1227                         }
1228                 }
1229
1230                 if (required && !value) goto is_required;
1231                 if (cant_be_empty && (value[0] == '\0')) goto cant_be_empty;
1232
1233                 if (attribute) {
1234                         if (!dict_attrbyname(value)) {
1235                                 if (!cp) {
1236                                         cf_log_err(&(cs->item), "No such attribute '%s' for configuration '%s'",
1237                                                    value, name);
1238                                 } else {
1239                                         cf_log_err(&(cp->item), "No such attribute '%s'", value);
1240                                 }
1241                                 return -1;
1242                         }
1243                 }
1244
1245                 /*
1246                  *      Hide secrets when using "radiusd -X".
1247                  */
1248                 if (secret && (debug_flag <= 2)) {
1249                         cf_log_info(cs, "%.*s\t%s = <<< secret >>>",
1250                                     cs->depth, parse_spaces, name);
1251                 } else {
1252                         cf_log_info(cs, "%.*s\t%s = \"%s\"",
1253                                     cs->depth, parse_spaces, name, value ? value : "(null)");
1254                 }
1255                 *q = value ? talloc_typed_strdup(cs, value) : NULL;
1256
1257                 /*
1258                  *      If there's data AND it's an input file, check
1259                  *      that we can read it.  This check allows errors
1260                  *      to be caught as early as possible, during
1261                  *      server startup.
1262                  */
1263                 if (*q && input) {
1264                         struct stat buf;
1265
1266                         if (stat(*q, &buf) < 0) {
1267                                 ERROR("Unable to open file \"%s\": %s",
1268                                       value, fr_syserror(errno));
1269                                 return -1;
1270                         }
1271                 }
1272                 break;
1273
1274         case PW_TYPE_IPV4_ADDR:
1275         case PW_TYPE_IPV4_PREFIX:
1276                 ipaddr = data;
1277
1278                 if (fr_pton4(ipaddr, value, -1, true, false) < 0) {
1279                         ERROR("%s", fr_strerror());
1280                         return -1;
1281                 }
1282                 if (fr_item_validate_ipaddr(cs, name, type, value, ipaddr) < 0) return -1;
1283                 break;
1284
1285         case PW_TYPE_IPV6_ADDR:
1286         case PW_TYPE_IPV6_PREFIX:
1287                 ipaddr = data;
1288
1289                 if (fr_pton6(ipaddr, value, -1, true, false) < 0) {
1290                         ERROR("%s", fr_strerror());
1291                         return -1;
1292                 }
1293                 if (fr_item_validate_ipaddr(cs, name, type, value, ipaddr) < 0) return -1;
1294                 break;
1295
1296         case PW_TYPE_COMBO_IP_ADDR:
1297         case PW_TYPE_COMBO_IP_PREFIX:
1298                 ipaddr = data;
1299
1300                 if (fr_pton(ipaddr, value, -1, true) < 0) {
1301                         ERROR("%s", fr_strerror());
1302                         return -1;
1303                 }
1304                 if (fr_item_validate_ipaddr(cs, name, type, value, ipaddr) < 0) return -1;
1305                 break;
1306
1307         case PW_TYPE_TIMEVAL: {
1308                 int sec;
1309                 char *end;
1310                 struct timeval tv;
1311
1312                 sec = strtoul(value, &end, 10);
1313                 tv.tv_sec = sec;
1314                 tv.tv_usec = 0;
1315                 if (*end == '.') {
1316                         sec = strlen(end + 1);
1317
1318                         if (sec > 6) {
1319                                 ERROR("Too much precision for timeval");
1320                                 return -1;
1321                         }
1322
1323                         strcpy(buffer, "000000");
1324                         memcpy(buffer, end + 1, sec);
1325
1326                         sec = strtoul(buffer, NULL, 10);
1327                         tv.tv_usec = sec;
1328                 }
1329                 cf_log_info(cs, "%.*s\t%s = %d.%06d",
1330                             cs->depth, parse_spaces, name, (int) tv.tv_sec, (int) tv.tv_usec);
1331                 memcpy(data, &tv, sizeof(tv));
1332                 }
1333                 break;
1334
1335         default:
1336                 /*
1337                  *      If we get here, it's a sanity check error.
1338                  *      It's not an error parsing the configuration
1339                  *      file.
1340                  */
1341                 rad_assert(type > PW_TYPE_INVALID);
1342                 rad_assert(type < PW_TYPE_MAX);
1343
1344                 ERROR("type '%s' is not supported in the configuration files",
1345                        fr_int2str(dict_attr_types, type, "?Unknown?"));
1346                 return -1;
1347         } /* switch over variable type */
1348
1349         if (!cp) {
1350                 CONF_PAIR *cpn;
1351
1352                 cpn = cf_pair_alloc(cs, name, value, T_OP_SET, T_BARE_WORD);
1353                 if (!cpn) return -1;
1354                 cpn->item.filename = "<internal>";
1355                 cpn->item.lineno = 0;
1356                 cf_item_add(cs, &(cpn->item));
1357         }
1358
1359         return rcode;
1360 }
1361
1362
1363 /*
1364  *      A copy of cf_section_parse that initializes pointers before
1365  *      parsing them.
1366  */
1367 static void cf_section_parse_init(CONF_SECTION *cs, void *base,
1368                                   CONF_PARSER const *variables)
1369 {
1370         int i;
1371         void *data;
1372
1373         for (i = 0; variables[i].name != NULL; i++) {
1374                 if (variables[i].type == PW_TYPE_SUBSECTION) {
1375                         CONF_SECTION *subcs;
1376
1377                         if (!variables[i].dflt) continue;
1378
1379                         subcs = cf_section_sub_find(cs, variables[i].name);
1380
1381                         /*
1382                          *      If there's no subsection in the
1383                          *      config, BUT the CONF_PARSER wants one,
1384                          *      then create an empty one.  This is so
1385                          *      that we can track the strings,
1386                          *      etc. allocated in the subsection.
1387                          */
1388                         if (!subcs) {
1389                                 subcs = cf_section_alloc(cs, variables[i].name,
1390                                                          NULL);
1391                                 if (!subcs) return;
1392
1393                                 subcs->item.filename = cs->item.filename;
1394                                 subcs->item.lineno = cs->item.lineno;
1395                                 cf_item_add(cs, &(subcs->item));
1396                         }
1397
1398                         cf_section_parse_init(subcs, base,
1399                                               (CONF_PARSER const *) variables[i].dflt);
1400                         continue;
1401                 }
1402
1403                 if ((variables[i].type != PW_TYPE_STRING) &&
1404                     (variables[i].type != PW_TYPE_FILE_INPUT) &&
1405                     (variables[i].type != PW_TYPE_FILE_OUTPUT)) {
1406                         continue;
1407                 }
1408
1409                 if (variables[i].data) {
1410                         data = variables[i].data; /* prefer this. */
1411                 } else if (base) {
1412                         data = ((char *)base) + variables[i].offset;
1413                 } else {
1414                         continue;
1415                 }
1416
1417                 *(char **) data = NULL;
1418         } /* for all variables in the configuration section */
1419 }
1420
1421
1422 /*
1423  *      Parse a configuration section into user-supplied variables.
1424  */
1425 int cf_section_parse(CONF_SECTION *cs, void *base,
1426                      CONF_PARSER const *variables)
1427 {
1428         int ret;
1429         int i;
1430         void *data;
1431
1432         cs->variables = variables; /* this doesn't hurt anything */
1433
1434         if (!cs->name2) {
1435                 cf_log_info(cs, "%.*s%s {", cs->depth, parse_spaces,
1436                        cs->name1);
1437         } else {
1438                 cf_log_info(cs, "%.*s%s %s {", cs->depth, parse_spaces,
1439                        cs->name1, cs->name2);
1440         }
1441
1442         cf_section_parse_init(cs, base, variables);
1443
1444         /*
1445          *      Handle the known configuration parameters.
1446          */
1447         for (i = 0; variables[i].name != NULL; i++) {
1448                 /*
1449                  *      Handle subsections specially
1450                  */
1451                 if (variables[i].type == PW_TYPE_SUBSECTION) {
1452                         CONF_SECTION *subcs;
1453                         subcs = cf_section_sub_find(cs, variables[i].name);
1454
1455                         if (!variables[i].dflt || !subcs) {
1456                                 DEBUG2("Internal sanity check 1 failed in cf_section_parse %s",
1457                                        variables[i].name);
1458                                 goto error;
1459                         }
1460
1461                         if (cf_section_parse(subcs, base,
1462                                              (CONF_PARSER const *) variables[i].dflt) < 0) {
1463                                 goto error;
1464                         }
1465                         continue;
1466                 } /* else it's a CONF_PAIR */
1467
1468                 if (variables[i].data) {
1469                         data = variables[i].data; /* prefer this. */
1470                 } else if (base) {
1471                         data = ((char *)base) + variables[i].offset;
1472                 } else {
1473                         DEBUG2("Internal sanity check 2 failed in cf_section_parse");
1474                         goto error;
1475                 }
1476
1477                 /*
1478                  *      Parse the pair we found, or a default value.
1479                  */
1480                 ret = cf_item_parse(cs, variables[i].name, variables[i].type, data, variables[i].dflt);
1481                 if (ret < 0) {
1482                         /*
1483                          *      Be nice, and print the name of the new config item.
1484                          */
1485                         if ((ret == -2) && (variables[i + 1].offset == variables[i].offset) &&
1486                             (variables[i + 1].data == variables[i].data)) {
1487                                 cf_log_err(&(cs->item), "Replace \"%s\" with \"%s\"", variables[i].name,
1488                                            variables[i + 1].name);
1489                         }
1490
1491                         goto error;
1492                 }
1493         } /* for all variables in the configuration section */
1494
1495         cf_log_info(cs, "%.*s}", cs->depth, parse_spaces);
1496
1497         cs->base = base;
1498
1499         return 0;
1500
1501  error:
1502         cf_log_info(cs, "%.*s}", cs->depth, parse_spaces);
1503         return -1;
1504 }
1505
1506
1507 /*
1508  *      Check XLAT things in pass 2.  But don't cache the xlat stuff anywhere.
1509  */
1510 int cf_section_parse_pass2(CONF_SECTION *cs, void *base, CONF_PARSER const *variables)
1511 {
1512         int i;
1513         ssize_t slen;
1514         char const *error;
1515         char *value = NULL;
1516         xlat_exp_t *xlat;
1517
1518         /*
1519          *      Handle the known configuration parameters.
1520          */
1521         for (i = 0; variables[i].name != NULL; i++) {
1522                 CONF_PAIR *cp;
1523
1524                 /*
1525                  *      Handle subsections specially
1526                  */
1527                 if (variables[i].type == PW_TYPE_SUBSECTION) {
1528                         CONF_SECTION *subcs;
1529                         subcs = cf_section_sub_find(cs, variables[i].name);
1530
1531                         if (cf_section_parse_pass2(subcs, base,
1532                                                    (CONF_PARSER const *) variables[i].dflt) < 0) {
1533                                 return -1;
1534                         }
1535                         continue;
1536                 } /* else it's a CONF_PAIR */
1537
1538                 /*
1539                  *      Ignore everything but xlat expansions.
1540                  */
1541                 if ((variables[i].type & PW_TYPE_XLAT) == 0) continue;
1542
1543                 cp = cf_pair_find(cs, variables[i].name);
1544
1545         redo:
1546                 if (!cp || !cp->value) continue;
1547
1548                 if ((cp->value_type != T_DOUBLE_QUOTED_STRING) &&
1549                     (cp->value_type != T_BARE_WORD)) continue;
1550
1551                 value = talloc_strdup(cs, cp->value); /* modified by xlat_tokenize */
1552                 xlat = NULL;
1553
1554                 slen = xlat_tokenize(cs, value, &xlat, &error);
1555                 if (slen < 0) {
1556                         char *spaces, *text;
1557
1558                         fr_canonicalize_error(cs, &spaces, &text, slen, cp->value);
1559
1560                         cf_log_err(&cp->item, "Failed parsing expanded string:");
1561                         cf_log_err(&cp->item, "%s", text);
1562                         cf_log_err(&cp->item, "%s^ %s", spaces, error);
1563
1564                         talloc_free(spaces);
1565                         talloc_free(text);
1566                         talloc_free(value);
1567                         talloc_free(xlat);
1568                         return -1;
1569                 }
1570
1571                 talloc_free(value);
1572                 talloc_free(xlat);
1573
1574                 /*
1575                  *      If the "multi" flag is set, check all of them.
1576                  */
1577                 if ((variables[i].type & PW_TYPE_MULTI) != 0) {
1578                         cp = cf_pair_find_next(cs, cp, cp->attr);
1579                         goto redo;
1580                 }
1581         } /* for all variables in the configuration section */
1582
1583         return 0;
1584 }
1585
1586 /*
1587  *      Merge the template so everyting else "just works".
1588  */
1589 static bool cf_template_merge(CONF_SECTION *cs, CONF_SECTION const *template)
1590 {
1591         CONF_ITEM *ci;
1592
1593         if (!cs || !template) return true;
1594
1595         cs->template = NULL;
1596
1597         /*
1598          *      Walk over the template, adding its' entries to the
1599          *      current section.  But only if the entries don't
1600          *      already exist in the current section.
1601          */
1602         for (ci = template->children; ci; ci = ci->next) {
1603                 if (ci->type == CONF_ITEM_PAIR) {
1604                         CONF_PAIR *cp1, *cp2;
1605
1606                         /*
1607                          *      It exists, don't over-write it.
1608                          */
1609                         cp1 = cf_item_to_pair(ci);
1610                         if (cf_pair_find(cs, cp1->attr)) {
1611                                 continue;
1612                         }
1613
1614                         /*
1615                          *      Create a new pair with all of the data
1616                          *      of the old one.
1617                          */
1618                         cp2 = cf_pair_alloc(cs, cp1->attr, cp1->value, cp1->op, cp1->value_type);
1619                         if (!cp2) return false;
1620
1621                         cp2->item.filename = cp1->item.filename;
1622                         cp2->item.lineno = cp1->item.lineno;
1623
1624                         cf_item_add(cs, &(cp2->item));
1625                         continue;
1626                 }
1627
1628                 if (ci->type == CONF_ITEM_SECTION) {
1629                         CONF_SECTION *subcs1, *subcs2;
1630
1631                         subcs1 = cf_item_to_section(ci);
1632                         rad_assert(subcs1 != NULL);
1633
1634                         subcs2 = cf_section_sub_find_name2(cs, subcs1->name1, subcs1->name2);
1635                         if (subcs2) {
1636                                 /*
1637                                  *      sub-sections get merged.
1638                                  */
1639                                 if (!cf_template_merge(subcs2, subcs1)) {
1640                                         return false;
1641                                 }
1642                                 continue;
1643                         }
1644
1645                         /*
1646                          *      Our section doesn't have a matching
1647                          *      sub-section.  Copy it verbatim from
1648                          *      the template.
1649                          */
1650                         subcs2 = cf_section_dup(cs, subcs1,
1651                                                 cf_section_name1(subcs1), cf_section_name2(subcs1),
1652                                                 false);
1653                         if (!subcs2) return false;
1654
1655                         subcs2->item.filename = subcs1->item.filename;
1656                         subcs2->item.lineno = subcs1->item.lineno;
1657
1658                         cf_item_add(cs, &(subcs2->item));
1659                         continue;
1660                 }
1661
1662                 /* ignore everything else */
1663         }
1664
1665         return true;
1666 }
1667
1668 static char const *cf_local_file(char const *base, char const *filename,
1669                                  char *buffer, size_t bufsize)
1670 {
1671         size_t dirsize;
1672         char *p;
1673
1674         strlcpy(buffer, base, bufsize);
1675
1676         p = strrchr(buffer, FR_DIR_SEP);
1677         if (!p) return filename;
1678         if (p[1]) {             /* ./foo */
1679                 p[1] = '\0';
1680         }
1681
1682         dirsize = (p - buffer) + 1;
1683
1684         if ((dirsize + strlen(filename)) >= bufsize) {
1685                 return NULL;
1686         }
1687
1688         strlcpy(p + 1, filename, bufsize - dirsize);
1689
1690         return buffer;
1691 }
1692
1693
1694 /*
1695  *      Read a part of the config file.
1696  */
1697 static int cf_section_read(char const *filename, int *lineno, FILE *fp,
1698                            CONF_SECTION *current)
1699
1700 {
1701         CONF_SECTION *this, *css, *nextcs;
1702         CONF_PAIR *cpn;
1703         char const *ptr;
1704         char const *value;
1705         char buf[8192];
1706         char buf1[8192];
1707         char buf2[8192];
1708         char buf3[8192];
1709         char buf4[8192];
1710         FR_TOKEN t1, t2, t3;
1711         bool has_spaces = false;
1712         char *cbuf = buf;
1713         size_t len;
1714         fr_cond_t *cond = NULL;
1715
1716         this = current;         /* add items here */
1717
1718         /*
1719          *      Read, checking for line continuations ('\\' at EOL)
1720          */
1721         for (;;) {
1722                 int at_eof;
1723                 nextcs = NULL;
1724
1725                 /*
1726                  *      Get data, and remember if we are at EOF.
1727                  */
1728                 at_eof = (fgets(cbuf, sizeof(buf) - (cbuf - buf), fp) == NULL);
1729                 (*lineno)++;
1730
1731                 /*
1732                  *      We read the entire 8k worth of data: complain.
1733                  *      Note that we don't care if the last character
1734                  *      is \n: it's still forbidden.  This means that
1735                  *      the maximum allowed length of text is 8k-1, which
1736                  *      should be plenty.
1737                  */
1738                 len = strlen(cbuf);
1739                 if ((cbuf + len + 1) >= (buf + sizeof(buf))) {
1740                         ERROR("%s[%d]: Line too long",
1741                                filename, *lineno);
1742                         return -1;
1743                 }
1744
1745                 if (has_spaces) {
1746                         ptr = cbuf;
1747                         while (isspace((int) *ptr)) ptr++;
1748
1749                         if (ptr > cbuf) {
1750                                 memmove(cbuf, ptr, len - (ptr - cbuf));
1751                                 len -= (ptr - cbuf);
1752                         }
1753                 }
1754
1755                 /*
1756                  *      Not doing continuations: check for edge
1757                  *      conditions.
1758                  */
1759                 if (cbuf == buf) {
1760                         if (at_eof) break;
1761
1762                         ptr = buf;
1763                         while (*ptr && isspace((int) *ptr)) ptr++;
1764
1765                         if (!*ptr || (*ptr == '#')) continue;
1766
1767                 } else if (at_eof || (len == 0)) {
1768                         ERROR("%s[%d]: Continuation at EOF is illegal",
1769                                filename, *lineno);
1770                         return -1;
1771                 }
1772
1773                 /*
1774                  *      See if there's a continuation.
1775                  */
1776                 while ((len > 0) &&
1777                        ((cbuf[len - 1] == '\n') || (cbuf[len - 1] == '\r'))) {
1778                         len--;
1779                         cbuf[len] = '\0';
1780                 }
1781
1782                 if ((len > 0) && (cbuf[len - 1] == '\\')) {
1783                         /*
1784                          *      Check for "suppress spaces" magic.
1785                          */
1786                         if (!has_spaces && (len > 2) && (cbuf[len - 2] == '"')) {
1787                                 has_spaces = true;
1788                         }
1789
1790                         cbuf[len - 1] = '\0';
1791                         cbuf += len - 1;
1792                         continue;
1793                 }
1794
1795                 ptr = cbuf = buf;
1796                 has_spaces = false;
1797
1798         get_more:
1799                 /*
1800                  *      The parser is getting to be evil.
1801                  */
1802                 while ((*ptr == ' ') || (*ptr == '\t')) ptr++;
1803
1804                 if (((ptr[0] == '%') && (ptr[1] == '{')) ||
1805                     (ptr[0] == '`')) {
1806                         int hack;
1807
1808                         if (ptr[0] == '%') {
1809                                 hack = rad_copy_variable(buf1, ptr);
1810                         } else {
1811                                 hack = rad_copy_string(buf1, ptr);
1812                         }
1813                         if (hack < 0) {
1814                                 ERROR("%s[%d]: Invalid expansion: %s",
1815                                        filename, *lineno, ptr);
1816                                 return -1;
1817                         }
1818
1819                         ptr += hack;
1820
1821                         t2 = gettoken(&ptr, buf2, sizeof(buf2), true);
1822                         switch (t2) {
1823                         case T_EOL:
1824                         case T_HASH:
1825                                 goto do_bare_word;
1826
1827                         default:
1828                                 ERROR("%s[%d]: Invalid expansion: %s",
1829                                        filename, *lineno, ptr);
1830                                 return -1;
1831                         }
1832                 } else {
1833                         t1 = gettoken(&ptr, buf1, sizeof(buf1), true);
1834                 }
1835
1836                 /*
1837                  *      The caller eats "name1 name2 {", and calls us
1838                  *      for the data inside of the section.  So if we
1839                  *      receive a closing brace, then it must mean the
1840                  *      end of the section.
1841                  */
1842                if (t1 == T_RCBRACE) {
1843                        if (this == current) {
1844                                ERROR("%s[%d]: Too many closing braces",
1845                                       filename, *lineno);
1846                                return -1;
1847                        }
1848
1849                        /*
1850                         *       Merge the template into the existing
1851                         *       section.  This uses more memory, but
1852                         *       means that templates now work with
1853                         *       sub-sections, etc.
1854                         */
1855                        if (!cf_template_merge(this, this->template)) {
1856                                return -1;
1857                        }
1858
1859                        this = this->item.parent;
1860                        goto check_for_more;
1861                }
1862
1863                 /*
1864                  *      Allow for $INCLUDE files
1865                  *
1866                  *      This *SHOULD* work for any level include.
1867                  *      I really really really hate this file.  -cparker
1868                  */
1869                if ((strcasecmp(buf1, "$INCLUDE") == 0) ||
1870                    (strcasecmp(buf1, "$-INCLUDE") == 0)) {
1871                         bool relative = true;
1872
1873                         t2 = getword(&ptr, buf2, sizeof(buf2), true);
1874                         if (t2 != T_EOL) {
1875                                ERROR("%s[%d]: Unexpected text after $INCLUDE",
1876                                      filename, *lineno);
1877                                return -1;
1878                         }
1879
1880                         if (buf2[0] == '$') relative = false;
1881
1882                         value = cf_expand_variables(filename, lineno, this, buf4, sizeof(buf4), buf2);
1883                         if (!value) return -1;
1884
1885                         if (!FR_DIR_IS_RELATIVE(value)) relative = false;
1886
1887                         if (relative) {
1888                                 value = cf_local_file(filename, value, buf3,
1889                                                       sizeof(buf3));
1890                                 if (!value) {
1891                                         ERROR("%s[%d]: Directories too deep.",
1892                                                filename, *lineno);
1893                                         return -1;
1894                                 }
1895                         }
1896
1897
1898 #ifdef HAVE_DIRENT_H
1899                         /*
1900                          *      $INCLUDE foo/
1901                          *
1902                          *      Include ALL non-"dot" files in the directory.
1903                          *      careful!
1904                          */
1905                         if (value[strlen(value) - 1] == '/') {
1906                                 DIR             *dir;
1907                                 struct dirent   *dp;
1908                                 struct stat stat_buf;
1909
1910                                 DEBUG2("including files in directory %s", value );
1911 #ifdef S_IWOTH
1912                                 /*
1913                                  *      Security checks.
1914                                  */
1915                                 if (stat(value, &stat_buf) < 0) {
1916                                         ERROR("%s[%d]: Failed reading directory %s: %s",
1917                                                filename, *lineno,
1918                                                value, fr_syserror(errno));
1919                                         return -1;
1920                                 }
1921
1922                                 if ((stat_buf.st_mode & S_IWOTH) != 0) {
1923                                         ERROR("%s[%d]: Directory %s is globally writable.  Refusing to start due to "
1924                                               "insecure configuration", filename, *lineno, value);
1925                                         return -1;
1926                                 }
1927 #endif
1928                                 dir = opendir(value);
1929                                 if (!dir) {
1930                                         ERROR("%s[%d]: Error reading directory %s: %s",
1931                                                filename, *lineno, value,
1932                                                fr_syserror(errno));
1933                                         return -1;
1934                                 }
1935
1936                                 /*
1937                                  *      Read the directory, ignoring "." files.
1938                                  */
1939                                 while ((dp = readdir(dir)) != NULL) {
1940                                         char const *p;
1941
1942                                         if (dp->d_name[0] == '.') continue;
1943
1944                                         /*
1945                                          *      Check for valid characters
1946                                          */
1947                                         for (p = dp->d_name; *p != '\0'; p++) {
1948                                                 if (isalpha((int)*p) ||
1949                                                     isdigit((int)*p) ||
1950                                                     (*p == '-') ||
1951                                                     (*p == '_') ||
1952                                                     (*p == '.')) continue;
1953                                                 break;
1954                                         }
1955                                         if (*p != '\0') continue;
1956
1957                                         snprintf(buf2, sizeof(buf2), "%s%s",
1958                                                  value, dp->d_name);
1959                                         if ((stat(buf2, &stat_buf) != 0) ||
1960                                             S_ISDIR(stat_buf.st_mode)) continue;
1961                                         /*
1962                                          *      Read the file into the current
1963                                          *      configuration section.
1964                                          */
1965                                         if (cf_file_include(this, buf2) < 0) {
1966                                                 closedir(dir);
1967                                                 return -1;
1968                                         }
1969                                 }
1970                                 closedir(dir);
1971                         }  else
1972 #endif
1973                         { /* it was a normal file */
1974                                 if (buf1[1] == '-') {
1975                                         struct stat statbuf;
1976
1977                                         if (stat(value, &statbuf) < 0) {
1978                                                 WARN("Not including file %s: %s", value, fr_syserror(errno));
1979                                                 continue;
1980                                         }
1981                                 }
1982
1983                                 if (cf_file_include(this, value) < 0) {
1984                                         return -1;
1985                                 }
1986                         }
1987                         continue;
1988                 } /* we were in an include */
1989
1990                if (strcasecmp(buf1, "$template") == 0) {
1991                        CONF_ITEM *ci;
1992                        CONF_SECTION *parentcs, *templatecs;
1993                        t2 = getword(&ptr, buf2, sizeof(buf2), true);
1994
1995                        if (t2 != T_EOL) {
1996                                ERROR("%s[%d]: Unexpected text after $TEMPLATE", filename, *lineno);
1997                                return -1;
1998                        }
1999
2000                        parentcs = cf_top_section(current);
2001
2002                        templatecs = cf_section_sub_find(parentcs, "templates");
2003                        if (!templatecs) {
2004                                 ERROR("%s[%d]: No \"templates\" section for reference \"%s\"", filename, *lineno, buf2);
2005                                 return -1;
2006                        }
2007
2008                        ci = cf_reference_item(parentcs, templatecs, buf2);
2009                        if (!ci || (ci->type != CONF_ITEM_SECTION)) {
2010                                 ERROR("%s[%d]: Reference \"%s\" not found", filename, *lineno, buf2);
2011                                 return -1;
2012                        }
2013
2014                        if (!this) {
2015                                 ERROR("%s[%d]: Internal sanity check error in template reference", filename, *lineno);
2016                                 return -1;
2017                        }
2018
2019                        if (this->template) {
2020                                 ERROR("%s[%d]: Section already has a template", filename, *lineno);
2021                                 return -1;
2022                        }
2023
2024                        this->template = cf_item_to_section(ci);
2025                        continue;
2026                }
2027
2028                 /*
2029                  *      Ensure that the user can't add CONF_PAIRs
2030                  *      with 'internal' names;
2031                  */
2032                 if (buf1[0] == '_') {
2033                         ERROR("%s[%d]: Illegal configuration pair name \"%s\"", filename, *lineno, buf1);
2034                         return -1;
2035                 }
2036
2037                 /*
2038                  *      Handle if/elsif specially.
2039                  */
2040                 if ((strcmp(buf1, "if") == 0) || (strcmp(buf1, "elsif") == 0)) {
2041                         ssize_t slen;
2042                         char const *error = NULL;
2043                         char *p;
2044                         CONF_SECTION *server;
2045
2046                         /*
2047                          *      if / elsif MUST be inside of a
2048                          *      processing section, which MUST in turn
2049                          *      be inside of a "server" directive.
2050                          */
2051                         if (!this->item.parent) {
2052                         invalid_location:
2053                                 ERROR("%s[%d]: Invalid location for '%s'",
2054                                        filename, *lineno, buf1);
2055                                 return -1;
2056                         }
2057
2058                         /*
2059                          *      Skip (...) to find the {
2060                          */
2061                         slen = fr_condition_tokenize(nextcs, cf_section_to_item(nextcs), ptr, &cond,
2062                                                      &error, FR_COND_TWO_PASS);
2063                         memcpy(&p, &ptr, sizeof(p));
2064
2065                         if (slen < 0) {
2066                                 if (p[-slen] != '{') goto cond_error;
2067                                 slen = -slen;
2068                         }
2069                         TALLOC_FREE(cond);
2070
2071                         /*
2072                          *      This hack is so that the NEXT stage
2073                          *      doesn't go "too far" in expanding the
2074                          *      variable.  We can parse the conditions
2075                          *      without expanding the ${...} stuff.
2076                          *      BUT we don't want to expand all of the
2077                          *      stuff AFTER the condition.  So we do
2078                          *      two passes.
2079                          *
2080                          *      The first pass is to discover the end
2081                          *      of the condition.  We then expand THAT
2082                          *      string, and do a second pass parsing
2083                          *      the expanded condition.
2084                          */
2085                         p += slen;
2086                         *p = '\0';
2087
2088                         /*
2089                          *      If there's a ${...}.  If so, expand it.
2090                          */
2091                         if (strchr(ptr, '$') != NULL) {
2092                                 ptr = cf_expand_variables(filename, lineno,
2093                                                           this,
2094                                                           buf3, sizeof(buf3),
2095                                                           ptr);
2096                                 if (!ptr) {
2097                                         ERROR("%s[%d]: Parse error expanding ${...} in condition",
2098                                               filename, *lineno);
2099                                         return -1;
2100                                 }
2101                         } /* else leave it alone */
2102
2103                         server = this->item.parent;
2104                         while ((strcmp(server->name1, "server") != 0) &&
2105                                (strcmp(server->name1, "policy") != 0) &&
2106                                (strcmp(server->name1, "instantiate") != 0)) {
2107                                 server = server->item.parent;
2108                                 if (!server) goto invalid_location;
2109                         }
2110
2111                         nextcs = cf_section_alloc(this, buf1, ptr);
2112                         if (!nextcs) {
2113                                 ERROR("%s[%d]: Failed allocating memory for section",
2114                                       filename, *lineno);
2115                                 return -1;
2116                         }
2117                         nextcs->item.filename = talloc_strdup(nextcs, filename);
2118                         nextcs->item.lineno = *lineno;
2119
2120                         slen = fr_condition_tokenize(nextcs, cf_section_to_item(nextcs), ptr, &cond,
2121                                                      &error, FR_COND_TWO_PASS);
2122                         *p = '{'; /* put it back */
2123
2124                 cond_error:
2125                         if (slen < 0) {
2126                                 char *spaces, *text;
2127
2128                                 fr_canonicalize_error(nextcs, &spaces, &text, slen, ptr);
2129
2130                                 ERROR("%s[%d]: Parse error in condition",
2131                                       filename, *lineno);
2132                                 ERROR("%s[%d]: %s", filename, *lineno, text);
2133                                 ERROR("%s[%d]: %s^ %s", filename, *lineno, spaces, error);
2134
2135                                 talloc_free(spaces);
2136                                 talloc_free(text);
2137                                 talloc_free(nextcs);
2138                                 return -1;
2139                         }
2140
2141                         if ((size_t) slen >= (sizeof(buf2) - 1)) {
2142                                 talloc_free(nextcs);
2143                                 ERROR("%s[%d]: Condition is too large after \"%s\"",
2144                                        filename, *lineno, buf1);
2145                                 return -1;
2146                         }
2147
2148                         /*
2149                          *      Copy the expanded and parsed condition
2150                          *      into buf2.  Then, parse the text after
2151                          *      the condition, which now MUST be a '{.
2152                          *
2153                          *      If it wasn't '{' it would have been
2154                          *      caught in the first pass of
2155                          *      conditional parsing, above.
2156                          */
2157                         memcpy(buf2, ptr, slen);
2158                         buf2[slen] = '\0';
2159                         ptr = p;
2160                         t2 = T_BARE_WORD;
2161
2162                         if ((t3 = gettoken(&ptr, buf3, sizeof(buf3), true)) != T_LCBRACE) {
2163                                 talloc_free(nextcs);
2164                                 ERROR("%s[%d]: Expected '{' %d",
2165                                       filename, *lineno, t3);
2166                                 return -1;
2167                         }
2168
2169                         /*
2170                          *      Swap the condition with trailing stuff for
2171                          *      the final condition.
2172                          */
2173                         memcpy(&p, &nextcs->name2, sizeof(nextcs->name2));
2174                         talloc_free(p);
2175                         nextcs->name2 = talloc_typed_strdup(nextcs, buf2);
2176
2177                         goto section_alloc;
2178                 }
2179
2180                 /*
2181                  *      Grab the next token.
2182                  */
2183                 t2 = gettoken(&ptr, buf2, sizeof(buf2), !cf_new_escape);
2184                 switch (t2) {
2185                 case T_EOL:
2186                 case T_HASH:
2187                 case T_COMMA:
2188                 do_bare_word:
2189                         t3 = t2;
2190                         t2 = T_OP_EQ;
2191                         value = NULL;
2192                         goto do_set;
2193
2194                 case T_OP_INCRM:
2195                 case T_OP_ADD:
2196                 case T_OP_CMP_EQ:
2197                 case T_OP_SUB:
2198                 case T_OP_LE:
2199                 case T_OP_GE:
2200                 case T_OP_CMP_FALSE:
2201                         if (!this || (strcmp(this->name1, "update") != 0)) {
2202                                 ERROR("%s[%d]: Invalid operator in assignment",
2203                                        filename, *lineno);
2204                                 return -1;
2205                         }
2206                         /* FALL-THROUGH */
2207
2208                 case T_OP_EQ:
2209                 case T_OP_SET:
2210                         while (isspace((int) *ptr)) ptr++;
2211
2212                         /*
2213                          *      New parser: non-quoted strings are
2214                          *      bare words, and we parse everything
2215                          *      until the next newline, or the next
2216                          *      comma.  If they have { or } in a bare
2217                          *      word, well... too bad.
2218                          */
2219                         if (cf_new_escape && (*ptr != '"') && (*ptr != '\'')
2220                             && (*ptr != '`') && (*ptr != '/')) {
2221                                 const char *q = ptr;
2222
2223                                 t3 = T_BARE_WORD;
2224                                 while (*q && (*q >= ' ') && (*q != ',') &&
2225                                        !isspace(*q)) q++;
2226
2227                                 if ((size_t) (q - ptr) >= sizeof(buf3)) {
2228                                         ERROR("%s[%d]: Parse error: value too long",
2229                                               filename, *lineno);
2230                                         return -1;
2231                                 }
2232
2233                                 memcpy(buf3, ptr, (q - ptr));
2234                                 buf3[q - ptr] = '\0';
2235                                 ptr = q;
2236
2237                         } else {
2238                                 t3 = getstring(&ptr, buf3, sizeof(buf3), !cf_new_escape);
2239                         }
2240
2241                         if (t3 == T_INVALID) {
2242                                 ERROR("%s[%d]: Parse error: %s",
2243                                        filename, *lineno,
2244                                        fr_strerror());
2245                                 return -1;
2246                         }
2247
2248                         /*
2249                          *      These are not allowed.  Print a
2250                          *      helpful error message.
2251                          */
2252                         if ((t3 == T_BACK_QUOTED_STRING) &&
2253                             (!this || (strcmp(this->name1, "update") != 0))) {
2254                                 ERROR("%s[%d]: Syntax error: Invalid string `...` in assignment",
2255                                        filename, *lineno);
2256                                 return -1;
2257                         }
2258
2259                         /*
2260                          *      Handle variable substitution via ${foo}
2261                          */
2262                         switch (t3) {
2263                         case T_BARE_WORD:
2264                         case T_DOUBLE_QUOTED_STRING:
2265                         case T_BACK_QUOTED_STRING:
2266                                 value = cf_expand_variables(filename, lineno, this, buf4, sizeof(buf4), buf3);
2267                                 if (!value) return -1;
2268                                 break;
2269
2270                         case T_EOL:
2271                         case T_HASH:
2272                                 value = NULL;
2273                                 break;
2274
2275                         default:
2276                                 value = buf3;
2277                                 break;
2278                         }
2279
2280                         /*
2281                          *      Add this CONF_PAIR to our CONF_SECTION
2282                          */
2283                 do_set:
2284                         cpn = cf_pair_alloc(this, buf1, value, t2, t3);
2285                         if (!cpn) return -1;
2286                         cpn->item.filename = talloc_strdup(cpn, filename);
2287                         cpn->item.lineno = *lineno;
2288                         cf_item_add(this, &(cpn->item));
2289
2290                         /*
2291                          *      Hacks for escaping
2292                          */
2293                         if (!cf_new_escape && !this->item.parent && value &&
2294                             (strcmp(buf1, "correct_escapes") == 0) &&
2295                             ((strcmp(value, "true") == 0) ||
2296                              (strcmp(value, "yes") == 0) ||
2297                              (strcmp(value, "1") == 0))) {
2298                                 cf_new_escape = true;
2299                         }
2300
2301                         /*
2302                          *      Require a comma, unless there's a comment.
2303                          */
2304                         while (isspace(*ptr)) ptr++;
2305
2306                         if (*ptr == ',') {
2307                                 ptr++;
2308                                 break;
2309                         }
2310
2311                         /*
2312                          *      module # stuff!
2313                          *      foo = bar # other stuff
2314                          */
2315                         if ((t3 == T_HASH) || (t3 == T_COMMA) || (t3 == T_EOL) || (*ptr == '#')) continue;
2316
2317                         if (!*ptr || (*ptr == '}')) break;
2318
2319                         ERROR("%s[%d]: Syntax error: Expected comma after '%s': %s",
2320                               filename, *lineno, value, ptr);
2321                         return -1;
2322
2323                         /*
2324                          *      No '=', must be a section or sub-section.
2325                          */
2326                 case T_BARE_WORD:
2327                 case T_DOUBLE_QUOTED_STRING:
2328                 case T_SINGLE_QUOTED_STRING:
2329                         t3 = gettoken(&ptr, buf3, sizeof(buf3), true);
2330                         if (t3 != T_LCBRACE) {
2331                                 ERROR("%s[%d]: Expecting section start brace '{' after \"%s %s\"",
2332                                        filename, *lineno, buf1, buf2);
2333                                 return -1;
2334                         }
2335                         /* FALL-THROUGH */
2336
2337                 case T_LCBRACE:
2338                 section_alloc:
2339                         if (!cond) {
2340                                 css = cf_section_alloc(this, buf1,
2341                                                        t2 == T_LCBRACE ? NULL : buf2);
2342                                 if (!css) {
2343                                         ERROR("%s[%d]: Failed allocating memory for section",
2344                                               filename, *lineno);
2345                                         return -1;
2346                                 }
2347
2348                                 css->item.filename = talloc_strdup(css, filename);
2349                                 css->item.lineno = *lineno;
2350                                 cf_item_add(this, &(css->item));
2351
2352                         } else {
2353                                 css = nextcs;
2354                                 nextcs = NULL;
2355
2356                                 cf_item_add(this, &(css->item));
2357                                 cf_data_add_internal(css, "if", cond, NULL, false);
2358                                 cond = NULL; /* eaten by the above line */
2359                         }
2360
2361                         /*
2362                          *      There may not be a name2
2363                          */
2364                         css->name2_type = (t2 == T_LCBRACE) ? T_INVALID : t2;
2365
2366                         /*
2367                          *      The current section is now the child section.
2368                          */
2369                         this = css;
2370                         break;
2371
2372                 case T_INVALID:
2373                         ERROR("%s[%d]: Syntax error in '%s': %s", filename, *lineno, ptr, fr_strerror());
2374
2375                         return -1;
2376
2377                 default:
2378                         ERROR("%s[%d]: Parse error after \"%s\": unexpected token \"%s\"",
2379                               filename, *lineno, buf1, fr_int2str(fr_tokens, t2, "<INVALID>"));
2380
2381                         return -1;
2382                 }
2383
2384         check_for_more:
2385                 /*
2386                  *      Done parsing one thing.  Skip to EOL if possible.
2387                  */
2388                 while (isspace(*ptr)) ptr++;
2389
2390                 if (*ptr == '#') continue;
2391
2392                 if (*ptr) {
2393                         goto get_more;
2394                 }
2395
2396         }
2397
2398         /*
2399          *      See if EOF was unexpected ..
2400          */
2401         if (feof(fp) && (this != current)) {
2402                 ERROR("%s[%d]: EOF reached without closing brace for section %s starting at line %d",
2403                       filename, *lineno, cf_section_name1(this), cf_section_lineno(this));
2404                 return -1;
2405         }
2406
2407         return 0;
2408 }
2409
2410 /*
2411  *      Include one config file in another.
2412  */
2413 int cf_file_include(CONF_SECTION *cs, char const *filename)
2414 {
2415         FILE            *fp;
2416         int             lineno = 0;
2417         struct stat     statbuf;
2418         time_t          *mtime;
2419         CONF_DATA       *cd;
2420
2421         DEBUG2("including configuration file %s", filename);
2422
2423         fp = fopen(filename, "r");
2424         if (!fp) {
2425                 ERROR("Unable to open file \"%s\": %s",
2426                        filename, fr_syserror(errno));
2427                 return -1;
2428         }
2429
2430         if (stat(filename, &statbuf) == 0) {
2431 #ifdef S_IWOTH
2432                 if ((statbuf.st_mode & S_IWOTH) != 0) {
2433                         fclose(fp);
2434                         ERROR("Configuration file %s is globally writable.  "
2435                               "Refusing to start due to insecure configuration.", filename);
2436                         return -1;
2437                 }
2438 #endif
2439
2440 #if 0 && defined(S_IROTH)
2441                 if (statbuf.st_mode & S_IROTH) != 0) {
2442                         fclose(fp);
2443                         ERROR("Configuration file %s is globally readable.  "
2444                               "Refusing to start due to insecure configuration", filename);
2445                         return -1;
2446                 }
2447 #endif
2448         }
2449
2450         if (cf_data_find_internal(cs, filename, PW_TYPE_FILE_INPUT)) {
2451                 fclose(fp);
2452                 ERROR("Cannot include the same file twice: \"%s\"", filename);
2453
2454                 return -1;
2455         }
2456
2457         /*
2458          *      Add the filename to the section
2459          */
2460         mtime = talloc(cs, time_t);
2461         *mtime = statbuf.st_mtime;
2462
2463         if (cf_data_add_internal(cs, filename, mtime, NULL, PW_TYPE_FILE_INPUT) < 0) {
2464                 fclose(fp);
2465                 ERROR("Internal error opening file \"%s\"",
2466                        filename);
2467                 return -1;
2468         }
2469
2470         cd = cf_data_find_internal(cs, filename, PW_TYPE_FILE_INPUT);
2471         if (!cd) {
2472                 fclose(fp);
2473                 ERROR("Internal error opening file \"%s\"",
2474                        filename);
2475                 return -1;
2476         }
2477
2478         if (!cs->item.filename) cs->item.filename = talloc_strdup(cs, filename);
2479
2480         /*
2481          *      Read the section.  It's OK to have EOF without a
2482          *      matching close brace.
2483          */
2484         if (cf_section_read(cd->name, &lineno, fp, cs) < 0) {
2485                 fclose(fp);
2486                 return -1;
2487         }
2488
2489         fclose(fp);
2490         return 0;
2491 }
2492
2493 /*
2494  *      Bootstrap a config file.
2495  */
2496 CONF_SECTION *cf_file_read(char const *filename)
2497 {
2498         char *p;
2499         CONF_PAIR *cp;
2500         CONF_SECTION *cs;
2501
2502         cs = cf_section_alloc(NULL, "main", NULL);
2503         if (!cs) return NULL;
2504
2505         cp = cf_pair_alloc(cs, "confdir", filename, T_OP_SET, T_BARE_WORD);
2506         if (!cp) return NULL;
2507
2508         p = strrchr(cp->value, FR_DIR_SEP);
2509         if (p) *p = '\0';
2510
2511         cp->item.filename = "internal";
2512         cp->item.lineno = -1;
2513         cf_item_add(cs, &(cp->item));
2514
2515         if (cf_file_include(cs, filename) < 0) {
2516                 talloc_free(cs);
2517                 return NULL;
2518         }
2519
2520         return cs;
2521 }
2522
2523
2524 void cf_file_free(CONF_SECTION *cs)
2525 {
2526         talloc_free(cs);
2527 }
2528
2529
2530 /*
2531  * Return a CONF_PAIR within a CONF_SECTION.
2532  */
2533 CONF_PAIR *cf_pair_find(CONF_SECTION const *cs, char const *name)
2534 {
2535         CONF_PAIR *cp, mycp;
2536
2537         if (!cs || !name) return NULL;
2538
2539         mycp.attr = name;
2540         cp = rbtree_finddata(cs->pair_tree, &mycp);
2541         if (cp) return cp;
2542
2543         if (!cs->template) return NULL;
2544
2545         return rbtree_finddata(cs->template->pair_tree, &mycp);
2546 }
2547
2548 /*
2549  * Return the attr of a CONF_PAIR
2550  */
2551
2552 char const *cf_pair_attr(CONF_PAIR const *pair)
2553 {
2554         return (pair ? pair->attr : NULL);
2555 }
2556
2557 /*
2558  * Return the value of a CONF_PAIR
2559  */
2560
2561 char const *cf_pair_value(CONF_PAIR const *pair)
2562 {
2563         return (pair ? pair->value : NULL);
2564 }
2565
2566 FR_TOKEN cf_pair_operator(CONF_PAIR const *pair)
2567 {
2568         return (pair ? pair->op : T_INVALID);
2569 }
2570
2571 /*
2572  * Return the value type, should be one of the following:
2573  * T_BARE_WORD, T_SINGLE_QUOTED_STRING, T_BACK_QUOTED_STRING
2574  * T_DOUBLE_QUOTED_STRING or T_INVALID if the pair is NULL.
2575  */
2576 FR_TOKEN cf_pair_value_type(CONF_PAIR const *pair)
2577 {
2578         return (pair ? pair->value_type : T_INVALID);
2579 }
2580
2581 /*
2582  * Turn a CONF_PAIR into a VALUE_PAIR
2583  * For now, ignore the "value_type" field...
2584  */
2585 VALUE_PAIR *cf_pairtovp(CONF_PAIR *pair)
2586 {
2587         if (!pair) {
2588                 fr_strerror_printf("Internal error");
2589                 return NULL;
2590         }
2591
2592         if (!pair->value) {
2593                 fr_strerror_printf("No value given for attribute %s", pair->attr);
2594                 return NULL;
2595         }
2596
2597         /*
2598          *      false comparisons never match.  BUT if it's a "string"
2599          *      or `string`, then remember to expand it later.
2600          */
2601         if ((pair->op != T_OP_CMP_FALSE) &&
2602             ((pair->value_type == T_DOUBLE_QUOTED_STRING) ||
2603              (pair->value_type == T_BACK_QUOTED_STRING))) {
2604                 VALUE_PAIR *vp;
2605
2606                 vp = pairmake(pair, NULL, pair->attr, NULL, pair->op);
2607                 if (!vp) {
2608                         return NULL;
2609                 }
2610
2611                 if (pairmark_xlat(vp, pair->value) < 0) {
2612                         talloc_free(vp);
2613
2614                         return NULL;
2615                 }
2616
2617                 return vp;
2618         }
2619
2620         return pairmake(pair, NULL, pair->attr, pair->value, pair->op);
2621 }
2622
2623 /*
2624  * Return the first label of a CONF_SECTION
2625  */
2626
2627 char const *cf_section_name1(CONF_SECTION const *cs)
2628 {
2629         return (cs ? cs->name1 : NULL);
2630 }
2631
2632 /*
2633  * Return the second label of a CONF_SECTION
2634  */
2635
2636 char const *cf_section_name2(CONF_SECTION const *cs)
2637 {
2638         return (cs ? cs->name2 : NULL);
2639 }
2640
2641 /** Return name2 if set, else name1
2642  *
2643  */
2644 char const *cf_section_name(CONF_SECTION const *cs)
2645 {
2646         char const *name;
2647
2648         name = cf_section_name2(cs);
2649         if (name) return name;
2650
2651         return cf_section_name1(cs);
2652 }
2653
2654 /*
2655  * Find a value in a CONF_SECTION
2656  */
2657 char const *cf_section_value_find(CONF_SECTION const *cs, char const *attr)
2658 {
2659         CONF_PAIR       *cp;
2660
2661         cp = cf_pair_find(cs, attr);
2662
2663         return (cp ? cp->value : NULL);
2664 }
2665
2666
2667 CONF_SECTION *cf_section_find_name2(CONF_SECTION const *cs,
2668                                     char const *name1, char const *name2)
2669 {
2670         char const      *their2;
2671         CONF_ITEM const *ci;
2672
2673         if (!cs || !name1) return NULL;
2674
2675         for (ci = &(cs->item); ci; ci = ci->next) {
2676                 if (ci->type != CONF_ITEM_SECTION)
2677                         continue;
2678
2679                 if (strcmp(cf_item_to_section(ci)->name1, name1) != 0) {
2680                         continue;
2681                 }
2682
2683                 their2 = cf_item_to_section(ci)->name2;
2684
2685                 if ((!name2 && !their2) ||
2686                     (name2 && their2 && (strcmp(name2, their2) == 0))) {
2687                         return cf_item_to_section(ci);
2688                 }
2689         }
2690
2691         return NULL;
2692 }
2693
2694 /** Find a pair with a name matching attr, after specified pair.
2695  *
2696  * @param cs to search in.
2697  * @param pair to search from (may be NULL).
2698  * @param attr to find (may be NULL in which case any attribute matches).
2699  * @return the next matching CONF_PAIR or NULL if none matched.
2700  */
2701 CONF_PAIR *cf_pair_find_next(CONF_SECTION const *cs,
2702                              CONF_PAIR const *pair, char const *attr)
2703 {
2704         CONF_ITEM       *ci;
2705
2706         if (!cs) return NULL;
2707
2708         /*
2709          *      If pair is NULL and we're trying to find a specific
2710          *      attribute this must be a first time run.
2711          *
2712          *      Find the pair with correct name.
2713          */
2714         if (!pair && attr) return cf_pair_find(cs, attr);
2715
2716         /*
2717          *      Start searching from the next child, or from the head
2718          *      of the list of children (if no pair was provided).
2719          */
2720         for (ci = pair ? pair->item.next : cs->children;
2721              ci;
2722              ci = ci->next) {
2723                 if (ci->type != CONF_ITEM_PAIR) continue;
2724
2725                 if (!attr || strcmp(cf_item_to_pair(ci)->attr, attr) == 0) break;
2726         }
2727
2728         return cf_item_to_pair(ci);
2729 }
2730
2731 /*
2732  * Find a CONF_SECTION, or return the root if name is NULL
2733  */
2734
2735 CONF_SECTION *cf_section_find(char const *name)
2736 {
2737         if (name)
2738                 return cf_section_sub_find(root_config, name);
2739         else
2740                 return root_config;
2741 }
2742
2743 /** Find a sub-section in a section
2744  *
2745  *      This finds ANY section having the same first name.
2746  *      The second name is ignored.
2747  */
2748 CONF_SECTION *cf_section_sub_find(CONF_SECTION const *cs, char const *name)
2749 {
2750         CONF_SECTION mycs;
2751
2752         if (!cs || !name) return NULL;  /* can't find an un-named section */
2753
2754         /*
2755          *      No sub-sections have been defined, so none exist.
2756          */
2757         if (!cs->section_tree) return NULL;
2758
2759         mycs.name1 = name;
2760         mycs.name2 = NULL;
2761         return rbtree_finddata(cs->section_tree, &mycs);
2762 }
2763
2764
2765 /** Find a CONF_SECTION with both names.
2766  *
2767  */
2768 CONF_SECTION *cf_section_sub_find_name2(CONF_SECTION const *cs,
2769                                         char const *name1, char const *name2)
2770 {
2771         CONF_ITEM    *ci;
2772
2773         if (!cs) cs = root_config;
2774         if (!cs) return NULL;
2775
2776         if (name1) {
2777                 CONF_SECTION mycs, *master_cs;
2778
2779                 if (!cs->section_tree) return NULL;
2780
2781                 mycs.name1 = name1;
2782                 mycs.name2 = name2;
2783
2784                 master_cs = rbtree_finddata(cs->section_tree, &mycs);
2785                 if (!master_cs) return NULL;
2786
2787                 /*
2788                  *      Look it up in the name2 tree.  If it's there,
2789                  *      return it.
2790                  */
2791                 if (master_cs->name2_tree) {
2792                         CONF_SECTION *subcs;
2793
2794                         subcs = rbtree_finddata(master_cs->name2_tree, &mycs);
2795                         if (subcs) return subcs;
2796                 }
2797
2798                 /*
2799                  *      We don't insert ourselves into the name2 tree.
2800                  *      So if there's nothing in the name2 tree, maybe
2801                  *      *we* are the answer.
2802                  */
2803                 if (!master_cs->name2 && name2) return NULL;
2804                 if (master_cs->name2 && !name2) return NULL;
2805                 if (!master_cs->name2 && !name2) return master_cs;
2806
2807                 if (strcmp(master_cs->name2, name2) == 0) {
2808                         return master_cs;
2809                 }
2810
2811                 return NULL;
2812         }
2813
2814         /*
2815          *      Else do it the old-fashioned way.
2816          */
2817         for (ci = cs->children; ci; ci = ci->next) {
2818                 CONF_SECTION *subcs;
2819
2820                 if (ci->type != CONF_ITEM_SECTION)
2821                         continue;
2822
2823                 subcs = cf_item_to_section(ci);
2824                 if (!subcs->name2) {
2825                         if (strcmp(subcs->name1, name2) == 0) break;
2826                 } else {
2827                         if (strcmp(subcs->name2, name2) == 0) break;
2828                 }
2829         }
2830
2831         return cf_item_to_section(ci);
2832 }
2833
2834 /*
2835  * Return the next subsection after a CONF_SECTION
2836  * with a certain name1 (char *name1). If the requested
2837  * name1 is NULL, any name1 matches.
2838  */
2839
2840 CONF_SECTION *cf_subsection_find_next(CONF_SECTION const *section,
2841                                       CONF_SECTION const *subsection,
2842                                       char const *name1)
2843 {
2844         CONF_ITEM       *ci;
2845
2846         if (!section) return NULL;
2847
2848         /*
2849          * If subsection is NULL this must be a first time run
2850          * Find the subsection with correct name
2851          */
2852
2853         if (!subsection) {
2854                 ci = section->children;
2855         } else {
2856                 ci = subsection->item.next;
2857         }
2858
2859         for (; ci; ci = ci->next) {
2860                 if (ci->type != CONF_ITEM_SECTION)
2861                         continue;
2862                 if ((name1 == NULL) ||
2863                     (strcmp(cf_item_to_section(ci)->name1, name1) == 0))
2864                         break;
2865         }
2866
2867         return cf_item_to_section(ci);
2868 }
2869
2870
2871 /*
2872  * Return the next section after a CONF_SECTION
2873  * with a certain name1 (char *name1). If the requested
2874  * name1 is NULL, any name1 matches.
2875  */
2876
2877 CONF_SECTION *cf_section_find_next(CONF_SECTION const *section,
2878                                    CONF_SECTION const *subsection,
2879                                    char const *name1)
2880 {
2881         if (!section) return NULL;
2882
2883         if (!section->item.parent) return NULL;
2884
2885         return cf_subsection_find_next(section->item.parent, subsection, name1);
2886 }
2887
2888 /** Return the next item after a CONF_ITEM.
2889  *
2890  */
2891 CONF_ITEM *cf_item_find_next(CONF_SECTION const *section, CONF_ITEM const *item)
2892 {
2893         if (!section) return NULL;
2894
2895         /*
2896          *      If item is NULL this must be a first time run
2897          *      Return the first item
2898          */
2899         if (item == NULL) {
2900                 return section->children;
2901         } else {
2902                 return item->next;
2903         }
2904 }
2905
2906 static void _pair_count(int *count, CONF_SECTION const *cs)
2907 {
2908         CONF_ITEM const *ci;
2909
2910         for (ci = cf_item_find_next(cs, NULL);
2911              ci != NULL;
2912              ci = cf_item_find_next(cs, ci)) {
2913
2914                 if (cf_item_is_section(ci)) {
2915                         _pair_count(count, cf_item_to_section(ci));
2916                         continue;
2917                 }
2918
2919                 (*count)++;
2920         }
2921 }
2922
2923 /** Count the number of conf pairs beneath a section
2924  *
2925  * @param[in] cs to search for items in.
2926  * @return number of pairs nested within section.
2927  */
2928 int cf_pair_count(CONF_SECTION const *cs)
2929 {
2930         int count = 0;
2931
2932         _pair_count(&count, cs);
2933
2934         return count;
2935 }
2936
2937 CONF_SECTION *cf_item_parent(CONF_ITEM const *ci)
2938 {
2939         if (!ci) return NULL;
2940
2941         return ci->parent;
2942 }
2943
2944 int cf_section_lineno(CONF_SECTION const *section)
2945 {
2946         return section->item.lineno;
2947 }
2948
2949 char const *cf_pair_filename(CONF_PAIR const *pair)
2950 {
2951         return pair->item.filename;
2952 }
2953
2954 char const *cf_section_filename(CONF_SECTION const *section)
2955 {
2956         return section->item.filename;
2957 }
2958
2959 int cf_pair_lineno(CONF_PAIR const *pair)
2960 {
2961         return pair->item.lineno;
2962 }
2963
2964 bool cf_item_is_section(CONF_ITEM const *item)
2965 {
2966         return item->type == CONF_ITEM_SECTION;
2967 }
2968
2969 bool cf_item_is_pair(CONF_ITEM const *item)
2970 {
2971         return item->type == CONF_ITEM_PAIR;
2972 }
2973
2974
2975 static CONF_DATA *cf_data_alloc(CONF_SECTION *parent, char const *name,
2976                                 void *data, void (*data_free)(void *))
2977 {
2978         CONF_DATA *cd;
2979
2980         cd = talloc_zero(parent, CONF_DATA);
2981         if (!cd) return NULL;
2982
2983         cd->item.type = CONF_ITEM_DATA;
2984         cd->item.parent = parent;
2985         cd->name = talloc_typed_strdup(cd, name);
2986         if (!cd->name) {
2987                 talloc_free(cd);
2988                 return NULL;
2989         }
2990
2991         cd->data = data;
2992         cd->free = data_free;
2993
2994         if (cd->free) {
2995                 talloc_set_destructor(cd, _cf_data_free);
2996         }
2997
2998         return cd;
2999 }
3000
3001 static void *cf_data_find_internal(CONF_SECTION const *cs, char const *name, int flag)
3002 {
3003         if (!cs || !name) return NULL;
3004
3005         /*
3006          *      Find the name in the tree, for speed.
3007          */
3008         if (cs->data_tree) {
3009                 CONF_DATA mycd;
3010
3011                 mycd.name = name;
3012                 mycd.flag = flag;
3013                 return rbtree_finddata(cs->data_tree, &mycd);
3014         }
3015
3016         return NULL;
3017 }
3018
3019 /*
3020  *      Find data from a particular section.
3021  */
3022 void *cf_data_find(CONF_SECTION const *cs, char const *name)
3023 {
3024         CONF_DATA *cd = cf_data_find_internal(cs, name, 0);
3025
3026         if (cd) return cd->data;
3027         return NULL;
3028 }
3029
3030
3031 /*
3032  *      Add named data to a configuration section.
3033  */
3034 static int cf_data_add_internal(CONF_SECTION *cs, char const *name,
3035                                 void *data, void (*data_free)(void *),
3036                                 int flag)
3037 {
3038         CONF_DATA *cd;
3039
3040         if (!cs || !name) return -1;
3041
3042         /*
3043          *      Already exists.  Can't add it.
3044          */
3045         if (cf_data_find_internal(cs, name, flag) != NULL) return -1;
3046
3047         cd = cf_data_alloc(cs, name, data, data_free);
3048         if (!cd) return -1;
3049         cd->flag = flag;
3050
3051         cf_item_add(cs, cf_data_to_item(cd));
3052
3053         return 0;
3054 }
3055
3056 /*
3057  *      Add named data to a configuration section.
3058  */
3059 int cf_data_add(CONF_SECTION *cs, char const *name,
3060                 void *data, void (*data_free)(void *))
3061 {
3062         return cf_data_add_internal(cs, name, data, data_free, 0);
3063 }
3064
3065 /** Remove named data from a configuration section
3066  *
3067  */
3068 void *cf_data_remove(CONF_SECTION *cs, char const *name)
3069 {
3070         CONF_DATA mycd;
3071         CONF_DATA *cd;
3072         void *data;
3073
3074         if (!cs || !name) return NULL;
3075         if (!cs->data_tree) return NULL;
3076
3077         /*
3078          *      Find the name in the tree, for speed.
3079          */
3080         mycd.name = name;
3081         mycd.flag = 0;
3082         cd = rbtree_finddata(cs->data_tree, &mycd);
3083         if (!cd) return NULL;
3084
3085         talloc_set_destructor(cd, NULL);        /* Disarm the destructor */
3086         rbtree_deletebydata(cs->data_tree, &mycd);
3087
3088         data = cd->data;
3089         talloc_free(cd);
3090
3091         return data;
3092 }
3093
3094 /*
3095  *      This is here to make the rest of the code easier to read.  It
3096  *      ties conffile.c to log.c, but it means we don't have to
3097  *      pollute every other function with the knowledge of the
3098  *      configuration internals.
3099  */
3100 void cf_log_err(CONF_ITEM const *ci, char const *fmt, ...)
3101 {
3102         va_list ap;
3103         char buffer[256];
3104
3105         va_start(ap, fmt);
3106         vsnprintf(buffer, sizeof(buffer), fmt, ap);
3107         va_end(ap);
3108
3109         if (ci) {
3110                 ERROR("%s[%d]: %s",
3111                        ci->filename ? ci->filename : "unknown",
3112                        ci->lineno ? ci->lineno : 0,
3113                        buffer);
3114         } else {
3115                 ERROR("<unknown>[*]: %s", buffer);
3116         }
3117 }
3118
3119 void cf_log_err_cs(CONF_SECTION const *cs, char const *fmt, ...)
3120 {
3121         va_list ap;
3122         char buffer[256];
3123
3124         va_start(ap, fmt);
3125         vsnprintf(buffer, sizeof(buffer), fmt, ap);
3126         va_end(ap);
3127
3128         rad_assert(cs != NULL);
3129
3130         ERROR("%s[%d]: %s",
3131                cs->item.filename ? cs->item.filename : "unknown",
3132                cs->item.lineno ? cs->item.lineno : 0,
3133                buffer);
3134 }
3135
3136 void cf_log_err_cp(CONF_PAIR const *cp, char const *fmt, ...)
3137 {
3138         va_list ap;
3139         char buffer[256];
3140
3141         va_start(ap, fmt);
3142         vsnprintf(buffer, sizeof(buffer), fmt, ap);
3143         va_end(ap);
3144
3145         rad_assert(cp != NULL);
3146
3147         ERROR("%s[%d]: %s",
3148                cp->item.filename ? cp->item.filename : "unknown",
3149                cp->item.lineno ? cp->item.lineno : 0,
3150                buffer);
3151 }
3152
3153 void cf_log_info(CONF_SECTION const *cs, char const *fmt, ...)
3154 {
3155         va_list ap;
3156
3157         va_start(ap, fmt);
3158         if ((debug_flag > 1) && cs) vradlog(L_DBG, fmt, ap);
3159         va_end(ap);
3160 }
3161
3162 /*
3163  *      Wrapper to simplify the code.
3164  */
3165 void cf_log_module(CONF_SECTION const *cs, char const *fmt, ...)
3166 {
3167         va_list ap;
3168         char buffer[256];
3169
3170         va_start(ap, fmt);
3171         if (debug_flag > 1 && cs) {
3172                 vsnprintf(buffer, sizeof(buffer), fmt, ap);
3173
3174                 DEBUG("%.*s# %s", cs->depth, parse_spaces, buffer);
3175         }
3176         va_end(ap);
3177 }
3178
3179 const CONF_PARSER *cf_section_parse_table(CONF_SECTION *cs)
3180 {
3181         if (!cs) return NULL;
3182
3183         return cs->variables;
3184 }
3185
3186 /*
3187  *      For "switch" and "case" statements.
3188  */
3189 FR_TOKEN cf_section_name2_type(CONF_SECTION const *cs)
3190 {
3191         if (!cs) return T_INVALID;
3192
3193         return cs->name2_type;
3194 }