Formatting and documentation
[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, base,
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, base,
1579                                              (CONF_PARSER const *) variables[i].dflt) < 0) {
1580                                 goto error;
1581                         }
1582                         continue;
1583                 } /* else it's a CONF_PAIR */
1584
1585                 if (variables[i].data) {
1586                         data = variables[i].data; /* prefer this. */
1587                 } else if (base) {
1588                         data = ((char *)base) + variables[i].offset;
1589                 } else {
1590                         DEBUG2("Internal sanity check 2 failed in cf_section_parse");
1591                         goto error;
1592                 }
1593
1594                 /*
1595                  *      Parse the pair we found, or a default value.
1596                  */
1597                 ret = cf_item_parse(cs, variables[i].name, variables[i].type, data, variables[i].dflt);
1598                 if (ret < 0) {
1599                         /*
1600                          *      Be nice, and print the name of the new config item.
1601                          */
1602                         if ((ret == -2) && (variables[i + 1].offset == variables[i].offset) &&
1603                             (variables[i + 1].data == variables[i].data)) {
1604                                 cf_log_err(&(cs->item), "Replace \"%s\" with \"%s\"", variables[i].name,
1605                                            variables[i + 1].name);
1606                         }
1607
1608                         goto error;
1609                 }
1610         } /* for all variables in the configuration section */
1611
1612         cf_log_info(cs, "%.*s}", cs->depth, parse_spaces);
1613
1614         cs->base = base;
1615
1616         return 0;
1617
1618  error:
1619         cf_log_info(cs, "%.*s}", cs->depth, parse_spaces);
1620         return -1;
1621 }
1622
1623
1624 /*
1625  *      Check XLAT things in pass 2.  But don't cache the xlat stuff anywhere.
1626  */
1627 int cf_section_parse_pass2(CONF_SECTION *cs, void *base, CONF_PARSER const *variables)
1628 {
1629         int i;
1630         ssize_t slen;
1631         char const *error;
1632         char *value = NULL;
1633         xlat_exp_t *xlat;
1634
1635         /*
1636          *      Handle the known configuration parameters.
1637          */
1638         for (i = 0; variables[i].name != NULL; i++) {
1639                 CONF_PAIR *cp;
1640
1641                 /*
1642                  *      Handle subsections specially
1643                  */
1644                 if (variables[i].type == PW_TYPE_SUBSECTION) {
1645                         CONF_SECTION *subcs;
1646                         subcs = cf_section_sub_find(cs, variables[i].name);
1647
1648                         if (cf_section_parse_pass2(subcs, base,
1649                                                    (CONF_PARSER const *) variables[i].dflt) < 0) {
1650                                 return -1;
1651                         }
1652                         continue;
1653                 } /* else it's a CONF_PAIR */
1654
1655                 cp = cf_pair_find(cs, variables[i].name);
1656
1657         redo:
1658                 if (!cp || !cp->value) continue;
1659
1660                 if ((cp->rhs_type != T_DOUBLE_QUOTED_STRING) &&
1661                     (cp->rhs_type != T_BARE_WORD)) continue;
1662
1663                 /*
1664                  *      Non-xlat expansions shouldn't have xlat!
1665                  */
1666                 if (((variables[i].type & PW_TYPE_XLAT) == 0) &&
1667                     ((variables[i].type & PW_TYPE_TMPL) == 0)) {
1668                         /*
1669                          *      Ignore %{... in shared secrets.
1670                          *      They're never dynamically expanded.
1671                          */
1672                         if ((variables[i].type & PW_TYPE_SECRET) != 0) continue;
1673
1674                         if (strstr(cp->value, "%{") != NULL) {
1675                                 WARN("%s[%d]: Found dynamic expansion in string which will not be dynamically expanded",
1676                                      cp->item.filename ? cp->item.filename : "unknown",
1677                                      cp->item.lineno ? cp->item.lineno : 0);
1678                         }
1679                         continue;
1680                 }
1681
1682                 /*
1683                  *      xlat expansions should be parseable.
1684                  */
1685                 value = talloc_strdup(cs, cp->value); /* modified by xlat_tokenize */
1686                 xlat = NULL;
1687
1688                 slen = xlat_tokenize(cs, value, &xlat, &error);
1689                 if (slen < 0) {
1690                         char *spaces, *text;
1691
1692                         fr_canonicalize_error(cs, &spaces, &text, slen, cp->value);
1693
1694                         cf_log_err(&cp->item, "Failed parsing expanded string:");
1695                         cf_log_err(&cp->item, "%s", text);
1696                         cf_log_err(&cp->item, "%s^ %s", spaces, error);
1697
1698                         talloc_free(spaces);
1699                         talloc_free(text);
1700                         talloc_free(value);
1701                         talloc_free(xlat);
1702                         return -1;
1703                 }
1704
1705                 talloc_free(value);
1706                 talloc_free(xlat);
1707
1708                 /*
1709                  *      If the "multi" flag is set, check all of them.
1710                  */
1711                 if ((variables[i].type & PW_TYPE_MULTI) != 0) {
1712                         cp = cf_pair_find_next(cs, cp, cp->attr);
1713                         goto redo;
1714                 }
1715         } /* for all variables in the configuration section */
1716
1717         return 0;
1718 }
1719
1720 /*
1721  *      Merge the template so everyting else "just works".
1722  */
1723 static bool cf_template_merge(CONF_SECTION *cs, CONF_SECTION const *template)
1724 {
1725         CONF_ITEM *ci;
1726
1727         if (!cs || !template) return true;
1728
1729         cs->template = NULL;
1730
1731         /*
1732          *      Walk over the template, adding its' entries to the
1733          *      current section.  But only if the entries don't
1734          *      already exist in the current section.
1735          */
1736         for (ci = template->children; ci; ci = ci->next) {
1737                 if (ci->type == CONF_ITEM_PAIR) {
1738                         CONF_PAIR *cp1, *cp2;
1739
1740                         /*
1741                          *      It exists, don't over-write it.
1742                          */
1743                         cp1 = cf_item_to_pair(ci);
1744                         if (cf_pair_find(cs, cp1->attr)) {
1745                                 continue;
1746                         }
1747
1748                         /*
1749                          *      Create a new pair with all of the data
1750                          *      of the old one.
1751                          */
1752                         cp2 = cf_pair_dup(cs, cp1);
1753                         if (!cp2) return false;
1754
1755                         cp2->item.filename = cp1->item.filename;
1756                         cp2->item.lineno = cp1->item.lineno;
1757
1758                         cf_item_add(cs, &(cp2->item));
1759                         continue;
1760                 }
1761
1762                 if (ci->type == CONF_ITEM_SECTION) {
1763                         CONF_SECTION *subcs1, *subcs2;
1764
1765                         subcs1 = cf_item_to_section(ci);
1766                         rad_assert(subcs1 != NULL);
1767
1768                         subcs2 = cf_section_sub_find_name2(cs, subcs1->name1, subcs1->name2);
1769                         if (subcs2) {
1770                                 /*
1771                                  *      sub-sections get merged.
1772                                  */
1773                                 if (!cf_template_merge(subcs2, subcs1)) {
1774                                         return false;
1775                                 }
1776                                 continue;
1777                         }
1778
1779                         /*
1780                          *      Our section doesn't have a matching
1781                          *      sub-section.  Copy it verbatim from
1782                          *      the template.
1783                          */
1784                         subcs2 = cf_section_dup(cs, subcs1,
1785                                                 cf_section_name1(subcs1), cf_section_name2(subcs1),
1786                                                 false);
1787                         if (!subcs2) return false;
1788
1789                         subcs2->item.filename = subcs1->item.filename;
1790                         subcs2->item.lineno = subcs1->item.lineno;
1791
1792                         cf_item_add(cs, &(subcs2->item));
1793                         continue;
1794                 }
1795
1796                 /* ignore everything else */
1797         }
1798
1799         return true;
1800 }
1801
1802 static char const *cf_local_file(char const *base, char const *filename,
1803                                  char *buffer, size_t bufsize)
1804 {
1805         size_t dirsize;
1806         char *p;
1807
1808         strlcpy(buffer, base, bufsize);
1809
1810         p = strrchr(buffer, FR_DIR_SEP);
1811         if (!p) return filename;
1812         if (p[1]) {             /* ./foo */
1813                 p[1] = '\0';
1814         }
1815
1816         dirsize = (p - buffer) + 1;
1817
1818         if ((dirsize + strlen(filename)) >= bufsize) {
1819                 return NULL;
1820         }
1821
1822         strlcpy(p + 1, filename, bufsize - dirsize);
1823
1824         return buffer;
1825 }
1826
1827
1828 /*
1829  *      Read a part of the config file.
1830  */
1831 static int cf_section_read(char const *filename, int *lineno, FILE *fp,
1832                            CONF_SECTION *current)
1833
1834 {
1835         CONF_SECTION *this, *css, *nextcs;
1836         CONF_PAIR *cpn;
1837         char const *ptr;
1838         char const *value;
1839         char buf[8192];
1840         char buf1[8192];
1841         char buf2[8192];
1842         char buf3[8192];
1843         char buf4[8192];
1844         FR_TOKEN t1 = T_INVALID, t2, t3;
1845         bool has_spaces = false;
1846         char *cbuf = buf;
1847         size_t len;
1848         fr_cond_t *cond = NULL;
1849
1850         this = current;         /* add items here */
1851
1852         /*
1853          *      Read, checking for line continuations ('\\' at EOL)
1854          */
1855         for (;;) {
1856                 int at_eof;
1857                 nextcs = NULL;
1858
1859                 /*
1860                  *      Get data, and remember if we are at EOF.
1861                  */
1862                 at_eof = (fgets(cbuf, sizeof(buf) - (cbuf - buf), fp) == NULL);
1863                 (*lineno)++;
1864
1865                 /*
1866                  *      We read the entire 8k worth of data: complain.
1867                  *      Note that we don't care if the last character
1868                  *      is \n: it's still forbidden.  This means that
1869                  *      the maximum allowed length of text is 8k-1, which
1870                  *      should be plenty.
1871                  */
1872                 len = strlen(cbuf);
1873                 if ((cbuf + len + 1) >= (buf + sizeof(buf))) {
1874                         ERROR("%s[%d]: Line too long",
1875                                filename, *lineno);
1876                         return -1;
1877                 }
1878
1879                 if (has_spaces) {
1880                         ptr = cbuf;
1881                         while (isspace((int) *ptr)) ptr++;
1882
1883                         if (ptr > cbuf) {
1884                                 memmove(cbuf, ptr, len - (ptr - cbuf));
1885                                 len -= (ptr - cbuf);
1886                         }
1887                 }
1888
1889                 /*
1890                  *      Not doing continuations: check for edge
1891                  *      conditions.
1892                  */
1893                 if (cbuf == buf) {
1894                         if (at_eof) break;
1895
1896                         ptr = buf;
1897                         while (*ptr && isspace((int) *ptr)) ptr++;
1898
1899                         if (!*ptr || (*ptr == '#')) continue;
1900
1901                 } else if (at_eof || (len == 0)) {
1902                         ERROR("%s[%d]: Continuation at EOF is illegal",
1903                                filename, *lineno);
1904                         return -1;
1905                 }
1906
1907                 /*
1908                  *      See if there's a continuation.
1909                  */
1910                 while ((len > 0) &&
1911                        ((cbuf[len - 1] == '\n') || (cbuf[len - 1] == '\r'))) {
1912                         len--;
1913                         cbuf[len] = '\0';
1914                 }
1915
1916                 if ((len > 0) && (cbuf[len - 1] == '\\')) {
1917                         /*
1918                          *      Check for "suppress spaces" magic.
1919                          */
1920                         if (!has_spaces && (len > 2) && (cbuf[len - 2] == '"')) {
1921                                 has_spaces = true;
1922                         }
1923
1924                         cbuf[len - 1] = '\0';
1925                         cbuf += len - 1;
1926                         continue;
1927                 }
1928
1929                 ptr = cbuf = buf;
1930                 has_spaces = false;
1931
1932         get_more:
1933                 /*
1934                  *      The parser is getting to be evil.
1935                  */
1936                 while ((*ptr == ' ') || (*ptr == '\t')) ptr++;
1937
1938                 if (((ptr[0] == '%') && (ptr[1] == '{')) ||
1939                     (ptr[0] == '`')) {
1940                         int hack;
1941
1942                         if (ptr[0] == '%') {
1943                                 hack = rad_copy_variable(buf1, ptr);
1944                         } else {
1945                                 hack = rad_copy_string(buf1, ptr);
1946                         }
1947                         if (hack < 0) {
1948                                 ERROR("%s[%d]: Invalid expansion: %s",
1949                                        filename, *lineno, ptr);
1950                                 return -1;
1951                         }
1952
1953                         ptr += hack;
1954
1955                         t2 = gettoken(&ptr, buf2, sizeof(buf2), true);
1956                         switch (t2) {
1957                         case T_EOL:
1958                         case T_HASH:
1959                                 goto do_bare_word;
1960
1961                         default:
1962                                 ERROR("%s[%d]: Invalid expansion: %s",
1963                                        filename, *lineno, ptr);
1964                                 return -1;
1965                         }
1966                 } else {
1967                         t1 = gettoken(&ptr, buf1, sizeof(buf1), true);
1968                 }
1969
1970                 /*
1971                  *      The caller eats "name1 name2 {", and calls us
1972                  *      for the data inside of the section.  So if we
1973                  *      receive a closing brace, then it must mean the
1974                  *      end of the section.
1975                  */
1976                if (t1 == T_RCBRACE) {
1977                        if (this == current) {
1978                                ERROR("%s[%d]: Too many closing braces",
1979                                       filename, *lineno);
1980                                return -1;
1981                        }
1982
1983                        /*
1984                         *       Merge the template into the existing
1985                         *       section.  This uses more memory, but
1986                         *       means that templates now work with
1987                         *       sub-sections, etc.
1988                         */
1989                        if (!cf_template_merge(this, this->template)) {
1990                                return -1;
1991                        }
1992
1993                        this = this->item.parent;
1994                        goto check_for_more;
1995                }
1996
1997                 /*
1998                  *      Allow for $INCLUDE files
1999                  *
2000                  *      This *SHOULD* work for any level include.
2001                  *      I really really really hate this file.  -cparker
2002                  */
2003                if ((strcasecmp(buf1, "$INCLUDE") == 0) ||
2004                    (strcasecmp(buf1, "$-INCLUDE") == 0)) {
2005                         bool relative = true;
2006
2007                         t2 = getword(&ptr, buf2, sizeof(buf2), true);
2008                         if (t2 != T_EOL) {
2009                                ERROR("%s[%d]: Unexpected text after $INCLUDE",
2010                                      filename, *lineno);
2011                                return -1;
2012                         }
2013
2014                         if (buf2[0] == '$') relative = false;
2015
2016                         value = cf_expand_variables(filename, lineno, this, buf4, sizeof(buf4), buf2);
2017                         if (!value) return -1;
2018
2019                         if (!FR_DIR_IS_RELATIVE(value)) relative = false;
2020
2021                         if (relative) {
2022                                 value = cf_local_file(filename, value, buf3,
2023                                                       sizeof(buf3));
2024                                 if (!value) {
2025                                         ERROR("%s[%d]: Directories too deep.",
2026                                                filename, *lineno);
2027                                         return -1;
2028                                 }
2029                         }
2030
2031
2032 #ifdef HAVE_DIRENT_H
2033                         /*
2034                          *      $INCLUDE foo/
2035                          *
2036                          *      Include ALL non-"dot" files in the directory.
2037                          *      careful!
2038                          */
2039                         if (value[strlen(value) - 1] == '/') {
2040                                 DIR             *dir;
2041                                 struct dirent   *dp;
2042                                 struct stat stat_buf;
2043
2044                                 DEBUG2("including files in directory %s", value );
2045 #ifdef S_IWOTH
2046                                 /*
2047                                  *      Security checks.
2048                                  */
2049                                 if (stat(value, &stat_buf) < 0) {
2050                                         ERROR("%s[%d]: Failed reading directory %s: %s",
2051                                                filename, *lineno,
2052                                                value, fr_syserror(errno));
2053                                         return -1;
2054                                 }
2055
2056                                 if ((stat_buf.st_mode & S_IWOTH) != 0) {
2057                                         ERROR("%s[%d]: Directory %s is globally writable.  Refusing to start due to "
2058                                               "insecure configuration", filename, *lineno, value);
2059                                         return -1;
2060                                 }
2061 #endif
2062                                 dir = opendir(value);
2063                                 if (!dir) {
2064                                         ERROR("%s[%d]: Error reading directory %s: %s",
2065                                                filename, *lineno, value,
2066                                                fr_syserror(errno));
2067                                         return -1;
2068                                 }
2069
2070                                 /*
2071                                  *      Read the directory, ignoring "." files.
2072                                  */
2073                                 while ((dp = readdir(dir)) != NULL) {
2074                                         char const *p;
2075
2076                                         if (dp->d_name[0] == '.') continue;
2077
2078                                         /*
2079                                          *      Check for valid characters
2080                                          */
2081                                         for (p = dp->d_name; *p != '\0'; p++) {
2082                                                 if (isalpha((int)*p) ||
2083                                                     isdigit((int)*p) ||
2084                                                     (*p == '-') ||
2085                                                     (*p == '_') ||
2086                                                     (*p == '.')) continue;
2087                                                 break;
2088                                         }
2089                                         if (*p != '\0') continue;
2090
2091                                         snprintf(buf2, sizeof(buf2), "%s%s",
2092                                                  value, dp->d_name);
2093                                         if ((stat(buf2, &stat_buf) != 0) ||
2094                                             S_ISDIR(stat_buf.st_mode)) continue;
2095                                         /*
2096                                          *      Read the file into the current
2097                                          *      configuration section.
2098                                          */
2099                                         if (cf_file_include(this, buf2) < 0) {
2100                                                 closedir(dir);
2101                                                 return -1;
2102                                         }
2103                                 }
2104                                 closedir(dir);
2105                         }  else
2106 #endif
2107                         { /* it was a normal file */
2108                                 if (buf1[1] == '-') {
2109                                         struct stat statbuf;
2110
2111                                         if (stat(value, &statbuf) < 0) {
2112                                                 WARN("Not including file %s: %s", value, fr_syserror(errno));
2113                                                 continue;
2114                                         }
2115                                 }
2116
2117                                 if (cf_file_include(this, value) < 0) {
2118                                         return -1;
2119                                 }
2120                         }
2121                         continue;
2122                 } /* we were in an include */
2123
2124                if (strcasecmp(buf1, "$template") == 0) {
2125                        CONF_ITEM *ci;
2126                        CONF_SECTION *parentcs, *templatecs;
2127                        t2 = getword(&ptr, buf2, sizeof(buf2), true);
2128
2129                        if (t2 != T_EOL) {
2130                                ERROR("%s[%d]: Unexpected text after $TEMPLATE", filename, *lineno);
2131                                return -1;
2132                        }
2133
2134                        parentcs = cf_top_section(current);
2135
2136                        templatecs = cf_section_sub_find(parentcs, "templates");
2137                        if (!templatecs) {
2138                                 ERROR("%s[%d]: No \"templates\" section for reference \"%s\"", filename, *lineno, buf2);
2139                                 return -1;
2140                        }
2141
2142                        ci = cf_reference_item(parentcs, templatecs, buf2);
2143                        if (!ci || (ci->type != CONF_ITEM_SECTION)) {
2144                                 ERROR("%s[%d]: Reference \"%s\" not found", filename, *lineno, buf2);
2145                                 return -1;
2146                        }
2147
2148                        if (!this) {
2149                                 ERROR("%s[%d]: Internal sanity check error in template reference", filename, *lineno);
2150                                 return -1;
2151                        }
2152
2153                        if (this->template) {
2154                                 ERROR("%s[%d]: Section already has a template", filename, *lineno);
2155                                 return -1;
2156                        }
2157
2158                        this->template = cf_item_to_section(ci);
2159                        continue;
2160                }
2161
2162                 /*
2163                  *      Ensure that the user can't add CONF_PAIRs
2164                  *      with 'internal' names;
2165                  */
2166                 if (buf1[0] == '_') {
2167                         ERROR("%s[%d]: Illegal configuration pair name \"%s\"", filename, *lineno, buf1);
2168                         return -1;
2169                 }
2170
2171                 /*
2172                  *      Handle if/elsif specially.
2173                  */
2174                 if ((strcmp(buf1, "if") == 0) || (strcmp(buf1, "elsif") == 0)) {
2175                         ssize_t slen;
2176                         char const *error = NULL;
2177                         char *p;
2178                         CONF_SECTION *server;
2179
2180                         /*
2181                          *      if / elsif MUST be inside of a
2182                          *      processing section, which MUST in turn
2183                          *      be inside of a "server" directive.
2184                          */
2185                         if (!this->item.parent) {
2186                         invalid_location:
2187                                 ERROR("%s[%d]: Invalid location for '%s'",
2188                                        filename, *lineno, buf1);
2189                                 return -1;
2190                         }
2191
2192                         /*
2193                          *      Skip (...) to find the {
2194                          */
2195                         slen = fr_condition_tokenize(nextcs, cf_section_to_item(nextcs), ptr, &cond,
2196                                                      &error, FR_COND_TWO_PASS);
2197                         memcpy(&p, &ptr, sizeof(p));
2198
2199                         if (slen < 0) {
2200                                 if (p[-slen] != '{') goto cond_error;
2201                                 slen = -slen;
2202                         }
2203                         TALLOC_FREE(cond);
2204
2205                         /*
2206                          *      This hack is so that the NEXT stage
2207                          *      doesn't go "too far" in expanding the
2208                          *      variable.  We can parse the conditions
2209                          *      without expanding the ${...} stuff.
2210                          *      BUT we don't want to expand all of the
2211                          *      stuff AFTER the condition.  So we do
2212                          *      two passes.
2213                          *
2214                          *      The first pass is to discover the end
2215                          *      of the condition.  We then expand THAT
2216                          *      string, and do a second pass parsing
2217                          *      the expanded condition.
2218                          */
2219                         p += slen;
2220                         *p = '\0';
2221
2222                         /*
2223                          *      If there's a ${...}.  If so, expand it.
2224                          */
2225                         if (strchr(ptr, '$') != NULL) {
2226                                 ptr = cf_expand_variables(filename, lineno,
2227                                                           this,
2228                                                           buf3, sizeof(buf3),
2229                                                           ptr);
2230                                 if (!ptr) {
2231                                         ERROR("%s[%d]: Parse error expanding ${...} in condition",
2232                                               filename, *lineno);
2233                                         return -1;
2234                                 }
2235                         } /* else leave it alone */
2236
2237                         server = this->item.parent;
2238                         while ((strcmp(server->name1, "server") != 0) &&
2239                                (strcmp(server->name1, "policy") != 0) &&
2240                                (strcmp(server->name1, "instantiate") != 0)) {
2241                                 server = server->item.parent;
2242                                 if (!server) goto invalid_location;
2243                         }
2244
2245                         nextcs = cf_section_alloc(this, buf1, ptr);
2246                         if (!nextcs) {
2247                                 ERROR("%s[%d]: Failed allocating memory for section",
2248                                       filename, *lineno);
2249                                 return -1;
2250                         }
2251                         nextcs->item.filename = talloc_strdup(nextcs, filename);
2252                         nextcs->item.lineno = *lineno;
2253
2254                         slen = fr_condition_tokenize(nextcs, cf_section_to_item(nextcs), ptr, &cond,
2255                                                      &error, FR_COND_TWO_PASS);
2256                         *p = '{'; /* put it back */
2257
2258                 cond_error:
2259                         if (slen < 0) {
2260                                 char *spaces, *text;
2261
2262                                 fr_canonicalize_error(nextcs, &spaces, &text, slen, ptr);
2263
2264                                 ERROR("%s[%d]: Parse error in condition",
2265                                       filename, *lineno);
2266                                 ERROR("%s[%d]: %s", filename, *lineno, text);
2267                                 ERROR("%s[%d]: %s^ %s", filename, *lineno, spaces, error);
2268
2269                                 talloc_free(spaces);
2270                                 talloc_free(text);
2271                                 talloc_free(nextcs);
2272                                 return -1;
2273                         }
2274
2275                         if ((size_t) slen >= (sizeof(buf2) - 1)) {
2276                                 talloc_free(nextcs);
2277                                 ERROR("%s[%d]: Condition is too large after \"%s\"",
2278                                        filename, *lineno, buf1);
2279                                 return -1;
2280                         }
2281
2282                         /*
2283                          *      Copy the expanded and parsed condition
2284                          *      into buf2.  Then, parse the text after
2285                          *      the condition, which now MUST be a '{.
2286                          *
2287                          *      If it wasn't '{' it would have been
2288                          *      caught in the first pass of
2289                          *      conditional parsing, above.
2290                          */
2291                         memcpy(buf2, ptr, slen);
2292                         buf2[slen] = '\0';
2293                         ptr = p;
2294                         t2 = T_BARE_WORD;
2295
2296                         if ((t3 = gettoken(&ptr, buf3, sizeof(buf3), true)) != T_LCBRACE) {
2297                                 talloc_free(nextcs);
2298                                 ERROR("%s[%d]: Expected '{' %d",
2299                                       filename, *lineno, t3);
2300                                 return -1;
2301                         }
2302
2303                         /*
2304                          *      Swap the condition with trailing stuff for
2305                          *      the final condition.
2306                          */
2307                         memcpy(&p, &nextcs->name2, sizeof(nextcs->name2));
2308                         talloc_free(p);
2309                         nextcs->name2 = talloc_typed_strdup(nextcs, buf2);
2310
2311                         goto section_alloc;
2312                 }
2313
2314                 /*
2315                  *      Grab the next token.
2316                  */
2317                 t2 = gettoken(&ptr, buf2, sizeof(buf2), !cf_new_escape);
2318                 switch (t2) {
2319                 case T_EOL:
2320                 case T_HASH:
2321                 case T_COMMA:
2322                 do_bare_word:
2323                         t3 = t2;
2324                         t2 = T_OP_EQ;
2325                         value = NULL;
2326                         goto do_set;
2327
2328                 case T_OP_INCRM:
2329                 case T_OP_ADD:
2330                 case T_OP_CMP_EQ:
2331                 case T_OP_SUB:
2332                 case T_OP_LE:
2333                 case T_OP_GE:
2334                 case T_OP_CMP_FALSE:
2335                         if (!this || (strcmp(this->name1, "update") != 0)) {
2336                                 ERROR("%s[%d]: Invalid operator in assignment",
2337                                        filename, *lineno);
2338                                 return -1;
2339                         }
2340                         /* FALL-THROUGH */
2341
2342                 case T_OP_EQ:
2343                 case T_OP_SET:
2344                         while (isspace((int) *ptr)) ptr++;
2345
2346                         /*
2347                          *      New parser: non-quoted strings are
2348                          *      bare words, and we parse everything
2349                          *      until the next newline, or the next
2350                          *      comma.  If they have { or } in a bare
2351                          *      word, well... too bad.
2352                          */
2353                         if (cf_new_escape && (*ptr != '"') && (*ptr != '\'')
2354                             && (*ptr != '`') && (*ptr != '/')) {
2355                                 const char *q = ptr;
2356
2357                                 t3 = T_BARE_WORD;
2358                                 while (*q && (*q >= ' ') && (*q != ',') &&
2359                                        !isspace(*q)) q++;
2360
2361                                 if ((size_t) (q - ptr) >= sizeof(buf3)) {
2362                                         ERROR("%s[%d]: Parse error: value too long",
2363                                               filename, *lineno);
2364                                         return -1;
2365                                 }
2366
2367                                 memcpy(buf3, ptr, (q - ptr));
2368                                 buf3[q - ptr] = '\0';
2369                                 ptr = q;
2370
2371                         } else {
2372                                 t3 = getstring(&ptr, buf3, sizeof(buf3), !cf_new_escape);
2373                         }
2374
2375                         if (t3 == T_INVALID) {
2376                                 ERROR("%s[%d]: Parse error: %s",
2377                                        filename, *lineno,
2378                                        fr_strerror());
2379                                 return -1;
2380                         }
2381
2382                         /*
2383                          *      These are not allowed.  Print a
2384                          *      helpful error message.
2385                          */
2386                         if ((t3 == T_BACK_QUOTED_STRING) &&
2387                             (!this || (strcmp(this->name1, "update") != 0))) {
2388                                 ERROR("%s[%d]: Syntax error: Invalid string `...` in assignment",
2389                                        filename, *lineno);
2390                                 return -1;
2391                         }
2392
2393                         /*
2394                          *      Handle variable substitution via ${foo}
2395                          */
2396                         switch (t3) {
2397                         case T_BARE_WORD:
2398                         case T_DOUBLE_QUOTED_STRING:
2399                         case T_BACK_QUOTED_STRING:
2400                                 value = cf_expand_variables(filename, lineno, this, buf4, sizeof(buf4), buf3);
2401                                 if (!value) return -1;
2402                                 break;
2403
2404                         case T_EOL:
2405                         case T_HASH:
2406                                 value = NULL;
2407                                 break;
2408
2409                         default:
2410                                 value = buf3;
2411                                 break;
2412                         }
2413
2414                         /*
2415                          *      Add this CONF_PAIR to our CONF_SECTION
2416                          */
2417                 do_set:
2418                         cpn = cf_pair_alloc(this, buf1, value, t2, t1, t3);
2419                         if (!cpn) return -1;
2420                         cpn->item.filename = talloc_strdup(cpn, filename);
2421                         cpn->item.lineno = *lineno;
2422                         cf_item_add(this, &(cpn->item));
2423
2424                         /*
2425                          *      Hacks for escaping
2426                          */
2427                         if (!cf_new_escape && !this->item.parent && value &&
2428                             (strcmp(buf1, "correct_escapes") == 0) &&
2429                             ((strcmp(value, "true") == 0) ||
2430                              (strcmp(value, "yes") == 0) ||
2431                              (strcmp(value, "1") == 0))) {
2432                                 cf_new_escape = true;
2433                         }
2434
2435                         /*
2436                          *      Require a comma, unless there's a comment.
2437                          */
2438                         while (isspace(*ptr)) ptr++;
2439
2440                         if (*ptr == ',') {
2441                                 ptr++;
2442                                 break;
2443                         }
2444
2445                         /*
2446                          *      module # stuff!
2447                          *      foo = bar # other stuff
2448                          */
2449                         if ((t3 == T_HASH) || (t3 == T_COMMA) || (t3 == T_EOL) || (*ptr == '#')) continue;
2450
2451                         if (!*ptr || (*ptr == '}')) break;
2452
2453                         ERROR("%s[%d]: Syntax error: Expected comma after '%s': %s",
2454                               filename, *lineno, value, ptr);
2455                         return -1;
2456
2457                         /*
2458                          *      No '=', must be a section or sub-section.
2459                          */
2460                 case T_BARE_WORD:
2461                 case T_DOUBLE_QUOTED_STRING:
2462                 case T_SINGLE_QUOTED_STRING:
2463                         t3 = gettoken(&ptr, buf3, sizeof(buf3), true);
2464                         if (t3 != T_LCBRACE) {
2465                                 ERROR("%s[%d]: Expecting section start brace '{' after \"%s %s\"",
2466                                        filename, *lineno, buf1, buf2);
2467                                 return -1;
2468                         }
2469                         /* FALL-THROUGH */
2470
2471                 case T_LCBRACE:
2472                 section_alloc:
2473                         if (!cond) {
2474                                 css = cf_section_alloc(this, buf1,
2475                                                        t2 == T_LCBRACE ? NULL : buf2);
2476                                 if (!css) {
2477                                         ERROR("%s[%d]: Failed allocating memory for section",
2478                                               filename, *lineno);
2479                                         return -1;
2480                                 }
2481
2482                                 css->item.filename = talloc_strdup(css, filename);
2483                                 css->item.lineno = *lineno;
2484                                 cf_item_add(this, &(css->item));
2485
2486                         } else {
2487                                 css = nextcs;
2488                                 nextcs = NULL;
2489
2490                                 cf_item_add(this, &(css->item));
2491                                 cf_data_add_internal(css, "if", cond, NULL, false);
2492                                 cond = NULL; /* eaten by the above line */
2493                         }
2494
2495                         /*
2496                          *      There may not be a name2
2497                          */
2498                         css->name2_type = (t2 == T_LCBRACE) ? T_INVALID : t2;
2499
2500                         /*
2501                          *      The current section is now the child section.
2502                          */
2503                         this = css;
2504                         break;
2505
2506                 case T_INVALID:
2507                         ERROR("%s[%d]: Syntax error in '%s': %s", filename, *lineno, ptr, fr_strerror());
2508
2509                         return -1;
2510
2511                 default:
2512                         ERROR("%s[%d]: Parse error after \"%s\": unexpected token \"%s\"",
2513                               filename, *lineno, buf1, fr_int2str(fr_tokens, t2, "<INVALID>"));
2514
2515                         return -1;
2516                 }
2517
2518         check_for_more:
2519                 /*
2520                  *      Done parsing one thing.  Skip to EOL if possible.
2521                  */
2522                 while (isspace(*ptr)) ptr++;
2523
2524                 if (*ptr == '#') continue;
2525
2526                 if (*ptr) {
2527                         goto get_more;
2528                 }
2529
2530         }
2531
2532         /*
2533          *      See if EOF was unexpected ..
2534          */
2535         if (feof(fp) && (this != current)) {
2536                 ERROR("%s[%d]: EOF reached without closing brace for section %s starting at line %d",
2537                       filename, *lineno, cf_section_name1(this), cf_section_lineno(this));
2538                 return -1;
2539         }
2540
2541         return 0;
2542 }
2543
2544 /*
2545  *      Include one config file in another.
2546  */
2547 int cf_file_include(CONF_SECTION *cs, char const *filename)
2548 {
2549         FILE            *fp;
2550         int             lineno = 0;
2551         struct stat     statbuf;
2552         time_t          *mtime;
2553         CONF_DATA       *cd;
2554
2555         DEBUG2("including configuration file %s", filename);
2556
2557         fp = fopen(filename, "r");
2558         if (!fp) {
2559                 ERROR("Unable to open file \"%s\": %s",
2560                        filename, fr_syserror(errno));
2561                 return -1;
2562         }
2563
2564         if (stat(filename, &statbuf) == 0) {
2565 #ifdef S_IWOTH
2566                 if ((statbuf.st_mode & S_IWOTH) != 0) {
2567                         fclose(fp);
2568                         ERROR("Configuration file %s is globally writable.  "
2569                               "Refusing to start due to insecure configuration.", filename);
2570                         return -1;
2571                 }
2572 #endif
2573
2574 #if 0 && defined(S_IROTH)
2575                 if (statbuf.st_mode & S_IROTH) != 0) {
2576                         fclose(fp);
2577                         ERROR("Configuration file %s is globally readable.  "
2578                               "Refusing to start due to insecure configuration", filename);
2579                         return -1;
2580                 }
2581 #endif
2582         }
2583
2584         if (cf_data_find_internal(cs, filename, PW_TYPE_FILE_INPUT)) {
2585                 fclose(fp);
2586                 ERROR("Cannot include the same file twice: \"%s\"", filename);
2587
2588                 return -1;
2589         }
2590
2591         /*
2592          *      Add the filename to the section
2593          */
2594         mtime = talloc(cs, time_t);
2595         *mtime = statbuf.st_mtime;
2596
2597         if (cf_data_add_internal(cs, filename, mtime, NULL, PW_TYPE_FILE_INPUT) < 0) {
2598                 fclose(fp);
2599                 ERROR("Internal error opening file \"%s\"",
2600                        filename);
2601                 return -1;
2602         }
2603
2604         cd = cf_data_find_internal(cs, filename, PW_TYPE_FILE_INPUT);
2605         if (!cd) {
2606                 fclose(fp);
2607                 ERROR("Internal error opening file \"%s\"",
2608                        filename);
2609                 return -1;
2610         }
2611
2612         if (!cs->item.filename) cs->item.filename = talloc_strdup(cs, filename);
2613
2614         /*
2615          *      Read the section.  It's OK to have EOF without a
2616          *      matching close brace.
2617          */
2618         if (cf_section_read(cd->name, &lineno, fp, cs) < 0) {
2619                 fclose(fp);
2620                 return -1;
2621         }
2622
2623         fclose(fp);
2624         return 0;
2625 }
2626
2627 /*
2628  *      Bootstrap a config file.
2629  */
2630 int cf_file_read(CONF_SECTION *cs, char const *filename)
2631 {
2632         char *p;
2633         CONF_PAIR *cp;
2634
2635         cp = cf_pair_alloc(cs, "confdir", filename, T_OP_SET, T_BARE_WORD, T_SINGLE_QUOTED_STRING);
2636         if (!cp) return -1;
2637
2638         p = strrchr(cp->value, FR_DIR_SEP);
2639         if (p) *p = '\0';
2640
2641         cp->item.filename = "internal";
2642         cp->item.lineno = -1;
2643         cf_item_add(cs, &(cp->item));
2644
2645         if (cf_file_include(cs, filename) < 0) return -1;
2646
2647         return 0;
2648 }
2649
2650
2651 void cf_file_free(CONF_SECTION *cs)
2652 {
2653         talloc_free(cs);
2654 }
2655
2656
2657 /*
2658  * Return a CONF_PAIR within a CONF_SECTION.
2659  */
2660 CONF_PAIR *cf_pair_find(CONF_SECTION const *cs, char const *name)
2661 {
2662         CONF_PAIR *cp, mycp;
2663
2664         if (!cs || !name) return NULL;
2665
2666         mycp.attr = name;
2667         cp = rbtree_finddata(cs->pair_tree, &mycp);
2668         if (cp) return cp;
2669
2670         if (!cs->template) return NULL;
2671
2672         return rbtree_finddata(cs->template->pair_tree, &mycp);
2673 }
2674
2675 /*
2676  * Return the attr of a CONF_PAIR
2677  */
2678
2679 char const *cf_pair_attr(CONF_PAIR const *pair)
2680 {
2681         return (pair ? pair->attr : NULL);
2682 }
2683
2684 /*
2685  * Return the value of a CONF_PAIR
2686  */
2687
2688 char const *cf_pair_value(CONF_PAIR const *pair)
2689 {
2690         return (pair ? pair->value : NULL);
2691 }
2692
2693 FR_TOKEN cf_pair_operator(CONF_PAIR const *pair)
2694 {
2695         return (pair ? pair->op : T_INVALID);
2696 }
2697
2698 /** Return the value (lhs) type
2699  *
2700  * @param pair to extract value type from.
2701  * @return one of T_BARE_WORD, T_SINGLE_QUOTED_STRING, T_BACK_QUOTED_STRING
2702  *      T_DOUBLE_QUOTED_STRING or T_INVALID if the pair is NULL.
2703  */
2704 FR_TOKEN cf_pair_attr_type(CONF_PAIR const *pair)
2705 {
2706         return (pair ? pair->lhs_type : T_INVALID);
2707 }
2708
2709 /** Return the value (rhs) type
2710  *
2711  * @param pair to extract value type from.
2712  * @return one of T_BARE_WORD, T_SINGLE_QUOTED_STRING, T_BACK_QUOTED_STRING
2713  *      T_DOUBLE_QUOTED_STRING or T_INVALID if the pair is NULL.
2714  */
2715 FR_TOKEN cf_pair_value_type(CONF_PAIR const *pair)
2716 {
2717         return (pair ? pair->rhs_type : T_INVALID);
2718 }
2719
2720 /*
2721  * Turn a CONF_PAIR into a VALUE_PAIR
2722  * For now, ignore the "value_type" field...
2723  */
2724 VALUE_PAIR *cf_pairtovp(CONF_PAIR *pair)
2725 {
2726         if (!pair) {
2727                 fr_strerror_printf("Internal error");
2728                 return NULL;
2729         }
2730
2731         if (!pair->value) {
2732                 fr_strerror_printf("No value given for attribute %s", pair->attr);
2733                 return NULL;
2734         }
2735
2736         /*
2737          *      false comparisons never match.  BUT if it's a "string"
2738          *      or `string`, then remember to expand it later.
2739          */
2740         if ((pair->op != T_OP_CMP_FALSE) &&
2741             ((pair->rhs_type == T_DOUBLE_QUOTED_STRING) ||
2742              (pair->rhs_type == T_BACK_QUOTED_STRING))) {
2743                 VALUE_PAIR *vp;
2744
2745                 vp = pairmake(pair, NULL, pair->attr, NULL, pair->op);
2746                 if (!vp) {
2747                         return NULL;
2748                 }
2749
2750                 if (pairmark_xlat(vp, pair->value) < 0) {
2751                         talloc_free(vp);
2752
2753                         return NULL;
2754                 }
2755
2756                 return vp;
2757         }
2758
2759         return pairmake(pair, NULL, pair->attr, pair->value, pair->op);
2760 }
2761
2762 /*
2763  * Return the first label of a CONF_SECTION
2764  */
2765
2766 char const *cf_section_name1(CONF_SECTION const *cs)
2767 {
2768         return (cs ? cs->name1 : NULL);
2769 }
2770
2771 /*
2772  * Return the second label of a CONF_SECTION
2773  */
2774
2775 char const *cf_section_name2(CONF_SECTION const *cs)
2776 {
2777         return (cs ? cs->name2 : NULL);
2778 }
2779
2780 /** Return name2 if set, else name1
2781  *
2782  */
2783 char const *cf_section_name(CONF_SECTION const *cs)
2784 {
2785         char const *name;
2786
2787         name = cf_section_name2(cs);
2788         if (name) return name;
2789
2790         return cf_section_name1(cs);
2791 }
2792
2793 /*
2794  * Find a value in a CONF_SECTION
2795  */
2796 char const *cf_section_value_find(CONF_SECTION const *cs, char const *attr)
2797 {
2798         CONF_PAIR       *cp;
2799
2800         cp = cf_pair_find(cs, attr);
2801
2802         return (cp ? cp->value : NULL);
2803 }
2804
2805
2806 CONF_SECTION *cf_section_find_name2(CONF_SECTION const *cs,
2807                                     char const *name1, char const *name2)
2808 {
2809         char const      *their2;
2810         CONF_ITEM const *ci;
2811
2812         if (!cs || !name1) return NULL;
2813
2814         for (ci = &(cs->item); ci; ci = ci->next) {
2815                 if (ci->type != CONF_ITEM_SECTION)
2816                         continue;
2817
2818                 if (strcmp(cf_item_to_section(ci)->name1, name1) != 0) {
2819                         continue;
2820                 }
2821
2822                 their2 = cf_item_to_section(ci)->name2;
2823
2824                 if ((!name2 && !their2) ||
2825                     (name2 && their2 && (strcmp(name2, their2) == 0))) {
2826                         return cf_item_to_section(ci);
2827                 }
2828         }
2829
2830         return NULL;
2831 }
2832
2833 /** Find a pair with a name matching attr, after specified pair.
2834  *
2835  * @param cs to search in.
2836  * @param pair to search from (may be NULL).
2837  * @param attr to find (may be NULL in which case any attribute matches).
2838  * @return the next matching CONF_PAIR or NULL if none matched.
2839  */
2840 CONF_PAIR *cf_pair_find_next(CONF_SECTION const *cs,
2841                              CONF_PAIR const *pair, char const *attr)
2842 {
2843         CONF_ITEM       *ci;
2844
2845         if (!cs) return NULL;
2846
2847         /*
2848          *      If pair is NULL and we're trying to find a specific
2849          *      attribute this must be a first time run.
2850          *
2851          *      Find the pair with correct name.
2852          */
2853         if (!pair && attr) return cf_pair_find(cs, attr);
2854
2855         /*
2856          *      Start searching from the next child, or from the head
2857          *      of the list of children (if no pair was provided).
2858          */
2859         for (ci = pair ? pair->item.next : cs->children;
2860              ci;
2861              ci = ci->next) {
2862                 if (ci->type != CONF_ITEM_PAIR) continue;
2863
2864                 if (!attr || strcmp(cf_item_to_pair(ci)->attr, attr) == 0) break;
2865         }
2866
2867         return cf_item_to_pair(ci);
2868 }
2869
2870 /*
2871  * Find a CONF_SECTION, or return the root if name is NULL
2872  */
2873
2874 CONF_SECTION *cf_section_find(char const *name)
2875 {
2876         if (name)
2877                 return cf_section_sub_find(root_config, name);
2878         else
2879                 return root_config;
2880 }
2881
2882 /** Find a sub-section in a section
2883  *
2884  *      This finds ANY section having the same first name.
2885  *      The second name is ignored.
2886  */
2887 CONF_SECTION *cf_section_sub_find(CONF_SECTION const *cs, char const *name)
2888 {
2889         CONF_SECTION mycs;
2890
2891         if (!cs || !name) return NULL;  /* can't find an un-named section */
2892
2893         /*
2894          *      No sub-sections have been defined, so none exist.
2895          */
2896         if (!cs->section_tree) return NULL;
2897
2898         mycs.name1 = name;
2899         mycs.name2 = NULL;
2900         return rbtree_finddata(cs->section_tree, &mycs);
2901 }
2902
2903
2904 /** Find a CONF_SECTION with both names.
2905  *
2906  */
2907 CONF_SECTION *cf_section_sub_find_name2(CONF_SECTION const *cs,
2908                                         char const *name1, char const *name2)
2909 {
2910         CONF_ITEM    *ci;
2911
2912         if (!cs) cs = root_config;
2913         if (!cs) return NULL;
2914
2915         if (name1) {
2916                 CONF_SECTION mycs, *master_cs;
2917
2918                 if (!cs->section_tree) return NULL;
2919
2920                 mycs.name1 = name1;
2921                 mycs.name2 = name2;
2922
2923                 master_cs = rbtree_finddata(cs->section_tree, &mycs);
2924                 if (!master_cs) return NULL;
2925
2926                 /*
2927                  *      Look it up in the name2 tree.  If it's there,
2928                  *      return it.
2929                  */
2930                 if (master_cs->name2_tree) {
2931                         CONF_SECTION *subcs;
2932
2933                         subcs = rbtree_finddata(master_cs->name2_tree, &mycs);
2934                         if (subcs) return subcs;
2935                 }
2936
2937                 /*
2938                  *      We don't insert ourselves into the name2 tree.
2939                  *      So if there's nothing in the name2 tree, maybe
2940                  *      *we* are the answer.
2941                  */
2942                 if (!master_cs->name2 && name2) return NULL;
2943                 if (master_cs->name2 && !name2) return NULL;
2944                 if (!master_cs->name2 && !name2) return master_cs;
2945
2946                 if (strcmp(master_cs->name2, name2) == 0) {
2947                         return master_cs;
2948                 }
2949
2950                 return NULL;
2951         }
2952
2953         /*
2954          *      Else do it the old-fashioned way.
2955          */
2956         for (ci = cs->children; ci; ci = ci->next) {
2957                 CONF_SECTION *subcs;
2958
2959                 if (ci->type != CONF_ITEM_SECTION)
2960                         continue;
2961
2962                 subcs = cf_item_to_section(ci);
2963                 if (!subcs->name2) {
2964                         if (strcmp(subcs->name1, name2) == 0) break;
2965                 } else {
2966                         if (strcmp(subcs->name2, name2) == 0) break;
2967                 }
2968         }
2969
2970         return cf_item_to_section(ci);
2971 }
2972
2973 /*
2974  * Return the next subsection after a CONF_SECTION
2975  * with a certain name1 (char *name1). If the requested
2976  * name1 is NULL, any name1 matches.
2977  */
2978
2979 CONF_SECTION *cf_subsection_find_next(CONF_SECTION const *section,
2980                                       CONF_SECTION const *subsection,
2981                                       char const *name1)
2982 {
2983         CONF_ITEM       *ci;
2984
2985         if (!section) return NULL;
2986
2987         /*
2988          * If subsection is NULL this must be a first time run
2989          * Find the subsection with correct name
2990          */
2991
2992         if (!subsection) {
2993                 ci = section->children;
2994         } else {
2995                 ci = subsection->item.next;
2996         }
2997
2998         for (; ci; ci = ci->next) {
2999                 if (ci->type != CONF_ITEM_SECTION)
3000                         continue;
3001                 if ((name1 == NULL) ||
3002                     (strcmp(cf_item_to_section(ci)->name1, name1) == 0))
3003                         break;
3004         }
3005
3006         return cf_item_to_section(ci);
3007 }
3008
3009
3010 /*
3011  * Return the next section after a CONF_SECTION
3012  * with a certain name1 (char *name1). If the requested
3013  * name1 is NULL, any name1 matches.
3014  */
3015
3016 CONF_SECTION *cf_section_find_next(CONF_SECTION const *section,
3017                                    CONF_SECTION const *subsection,
3018                                    char const *name1)
3019 {
3020         if (!section) return NULL;
3021
3022         if (!section->item.parent) return NULL;
3023
3024         return cf_subsection_find_next(section->item.parent, subsection, name1);
3025 }
3026
3027 /** Return the next item after a CONF_ITEM.
3028  *
3029  */
3030 CONF_ITEM *cf_item_find_next(CONF_SECTION const *section, CONF_ITEM const *item)
3031 {
3032         if (!section) return NULL;
3033
3034         /*
3035          *      If item is NULL this must be a first time run
3036          *      Return the first item
3037          */
3038         if (item == NULL) {
3039                 return section->children;
3040         } else {
3041                 return item->next;
3042         }
3043 }
3044
3045 static void _pair_count(int *count, CONF_SECTION const *cs)
3046 {
3047         CONF_ITEM const *ci;
3048
3049         for (ci = cf_item_find_next(cs, NULL);
3050              ci != NULL;
3051              ci = cf_item_find_next(cs, ci)) {
3052
3053                 if (cf_item_is_section(ci)) {
3054                         _pair_count(count, cf_item_to_section(ci));
3055                         continue;
3056                 }
3057
3058                 (*count)++;
3059         }
3060 }
3061
3062 /** Count the number of conf pairs beneath a section
3063  *
3064  * @param[in] cs to search for items in.
3065  * @return number of pairs nested within section.
3066  */
3067 int cf_pair_count(CONF_SECTION const *cs)
3068 {
3069         int count = 0;
3070
3071         _pair_count(&count, cs);
3072
3073         return count;
3074 }
3075
3076 CONF_SECTION *cf_item_parent(CONF_ITEM const *ci)
3077 {
3078         if (!ci) return NULL;
3079
3080         return ci->parent;
3081 }
3082
3083 int cf_section_lineno(CONF_SECTION const *section)
3084 {
3085         return section->item.lineno;
3086 }
3087
3088 char const *cf_pair_filename(CONF_PAIR const *pair)
3089 {
3090         return pair->item.filename;
3091 }
3092
3093 char const *cf_section_filename(CONF_SECTION const *section)
3094 {
3095         return section->item.filename;
3096 }
3097
3098 int cf_pair_lineno(CONF_PAIR const *pair)
3099 {
3100         return pair->item.lineno;
3101 }
3102
3103 bool cf_item_is_section(CONF_ITEM const *item)
3104 {
3105         return item->type == CONF_ITEM_SECTION;
3106 }
3107
3108 bool cf_item_is_pair(CONF_ITEM const *item)
3109 {
3110         return item->type == CONF_ITEM_PAIR;
3111 }
3112
3113
3114 static CONF_DATA *cf_data_alloc(CONF_SECTION *parent, char const *name,
3115                                 void *data, void (*data_free)(void *))
3116 {
3117         CONF_DATA *cd;
3118
3119         cd = talloc_zero(parent, CONF_DATA);
3120         if (!cd) return NULL;
3121
3122         cd->item.type = CONF_ITEM_DATA;
3123         cd->item.parent = parent;
3124         cd->name = talloc_typed_strdup(cd, name);
3125         if (!cd->name) {
3126                 talloc_free(cd);
3127                 return NULL;
3128         }
3129
3130         cd->data = data;
3131         cd->free = data_free;
3132
3133         if (cd->free) {
3134                 talloc_set_destructor(cd, _cf_data_free);
3135         }
3136
3137         return cd;
3138 }
3139
3140 static void *cf_data_find_internal(CONF_SECTION const *cs, char const *name, int flag)
3141 {
3142         if (!cs || !name) return NULL;
3143
3144         /*
3145          *      Find the name in the tree, for speed.
3146          */
3147         if (cs->data_tree) {
3148                 CONF_DATA mycd;
3149
3150                 mycd.name = name;
3151                 mycd.flag = flag;
3152                 return rbtree_finddata(cs->data_tree, &mycd);
3153         }
3154
3155         return NULL;
3156 }
3157
3158 /*
3159  *      Find data from a particular section.
3160  */
3161 void *cf_data_find(CONF_SECTION const *cs, char const *name)
3162 {
3163         CONF_DATA *cd = cf_data_find_internal(cs, name, 0);
3164
3165         if (cd) return cd->data;
3166         return NULL;
3167 }
3168
3169
3170 /*
3171  *      Add named data to a configuration section.
3172  */
3173 static int cf_data_add_internal(CONF_SECTION *cs, char const *name,
3174                                 void *data, void (*data_free)(void *),
3175                                 int flag)
3176 {
3177         CONF_DATA *cd;
3178
3179         if (!cs || !name) return -1;
3180
3181         /*
3182          *      Already exists.  Can't add it.
3183          */
3184         if (cf_data_find_internal(cs, name, flag) != NULL) return -1;
3185
3186         cd = cf_data_alloc(cs, name, data, data_free);
3187         if (!cd) return -1;
3188         cd->flag = flag;
3189
3190         cf_item_add(cs, cf_data_to_item(cd));
3191
3192         return 0;
3193 }
3194
3195 /*
3196  *      Add named data to a configuration section.
3197  */
3198 int cf_data_add(CONF_SECTION *cs, char const *name,
3199                 void *data, void (*data_free)(void *))
3200 {
3201         return cf_data_add_internal(cs, name, data, data_free, 0);
3202 }
3203
3204 /** Remove named data from a configuration section
3205  *
3206  */
3207 void *cf_data_remove(CONF_SECTION *cs, char const *name)
3208 {
3209         CONF_DATA mycd;
3210         CONF_DATA *cd;
3211         void *data;
3212
3213         if (!cs || !name) return NULL;
3214         if (!cs->data_tree) return NULL;
3215
3216         /*
3217          *      Find the name in the tree, for speed.
3218          */
3219         mycd.name = name;
3220         mycd.flag = 0;
3221         cd = rbtree_finddata(cs->data_tree, &mycd);
3222         if (!cd) return NULL;
3223
3224         talloc_set_destructor(cd, NULL);        /* Disarm the destructor */
3225         rbtree_deletebydata(cs->data_tree, &mycd);
3226
3227         data = cd->data;
3228         talloc_free(cd);
3229
3230         return data;
3231 }
3232
3233 /*
3234  *      This is here to make the rest of the code easier to read.  It
3235  *      ties conffile.c to log.c, but it means we don't have to
3236  *      pollute every other function with the knowledge of the
3237  *      configuration internals.
3238  */
3239 void cf_log_err(CONF_ITEM const *ci, char const *fmt, ...)
3240 {
3241         va_list ap;
3242         char buffer[256];
3243
3244         va_start(ap, fmt);
3245         vsnprintf(buffer, sizeof(buffer), fmt, ap);
3246         va_end(ap);
3247
3248         if (ci) {
3249                 ERROR("%s[%d]: %s",
3250                        ci->filename ? ci->filename : "unknown",
3251                        ci->lineno ? ci->lineno : 0,
3252                        buffer);
3253         } else {
3254                 ERROR("<unknown>[*]: %s", buffer);
3255         }
3256 }
3257
3258 void cf_log_err_cs(CONF_SECTION const *cs, char const *fmt, ...)
3259 {
3260         va_list ap;
3261         char buffer[256];
3262
3263         va_start(ap, fmt);
3264         vsnprintf(buffer, sizeof(buffer), fmt, ap);
3265         va_end(ap);
3266
3267         rad_assert(cs != NULL);
3268
3269         ERROR("%s[%d]: %s",
3270                cs->item.filename ? cs->item.filename : "unknown",
3271                cs->item.lineno ? cs->item.lineno : 0,
3272                buffer);
3273 }
3274
3275 void cf_log_err_cp(CONF_PAIR const *cp, char const *fmt, ...)
3276 {
3277         va_list ap;
3278         char buffer[256];
3279
3280         va_start(ap, fmt);
3281         vsnprintf(buffer, sizeof(buffer), fmt, ap);
3282         va_end(ap);
3283
3284         rad_assert(cp != NULL);
3285
3286         ERROR("%s[%d]: %s",
3287                cp->item.filename ? cp->item.filename : "unknown",
3288                cp->item.lineno ? cp->item.lineno : 0,
3289                buffer);
3290 }
3291
3292 void cf_log_info(CONF_SECTION const *cs, char const *fmt, ...)
3293 {
3294         va_list ap;
3295
3296         va_start(ap, fmt);
3297         if ((debug_flag > 1) && cs) vradlog(L_DBG, fmt, ap);
3298         va_end(ap);
3299 }
3300
3301 /*
3302  *      Wrapper to simplify the code.
3303  */
3304 void cf_log_module(CONF_SECTION const *cs, char const *fmt, ...)
3305 {
3306         va_list ap;
3307         char buffer[256];
3308
3309         va_start(ap, fmt);
3310         if (debug_flag > 1 && cs) {
3311                 vsnprintf(buffer, sizeof(buffer), fmt, ap);
3312
3313                 DEBUG("%.*s# %s", cs->depth, parse_spaces, buffer);
3314         }
3315         va_end(ap);
3316 }
3317
3318 const CONF_PARSER *cf_section_parse_table(CONF_SECTION *cs)
3319 {
3320         if (!cs) return NULL;
3321
3322         return cs->variables;
3323 }
3324
3325 /*
3326  *      For "switch" and "case" statements.
3327  */
3328 FR_TOKEN cf_section_name2_type(CONF_SECTION const *cs)
3329 {
3330         if (!cs) return T_INVALID;
3331
3332         return cs->name2_type;
3333 }