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