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