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