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