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