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