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