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