More portability fixes
[freeradius.git] / src / main / conffile.c
1 /*
2  * conffile.c   Read the radiusd.conf file.
3  *
4  *              Yep I should learn to use lex & yacc, or at least
5  *              write a decent parser. I know how to do that, really :)
6  *              miquels@cistron.nl
7  *
8  * Version:     $Id$
9  *
10  *   This program is free software; you can redistribute it and/or modify
11  *   it under the terms of the GNU General Public License as published by
12  *   the Free Software Foundation; either version 2 of the License, or
13  *   (at your option) any later version.
14  *
15  *   This program is distributed in the hope that it will be useful,
16  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *   GNU General Public License for more details.
19  *
20  *   You should have received a copy of the GNU General Public License
21  *   along with this program; if not, write to the Free Software
22  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  *
24  * Copyright 2000,2006  The FreeRADIUS server project
25  * Copyright 2000  Miquel van Smoorenburg <miquels@cistron.nl>
26  * Copyright 2000  Alan DeKok <aland@ox.org>
27  */
28
29 #include <freeradius-devel/ident.h>
30 RCSID("$Id$")
31
32 #include <freeradius-devel/radiusd.h>
33 #include <freeradius-devel/rad_assert.h>
34
35 #ifdef HAVE_DIRENT_H
36 #include <dirent.h>
37 #endif
38
39 #ifdef HAVE_SYS_STAT_H
40 #include <sys/stat.h>
41 #endif
42
43 #include <ctype.h>
44
45 typedef enum conf_type {
46         CONF_ITEM_INVALID = 0,
47         CONF_ITEM_PAIR,
48         CONF_ITEM_SECTION,
49         CONF_ITEM_DATA
50 } CONF_ITEM_TYPE;
51
52 struct conf_item {
53         struct conf_item *next;
54         struct conf_part *parent;
55         int lineno;
56         const char *filename;
57         CONF_ITEM_TYPE type;
58 };
59 struct conf_pair {
60         CONF_ITEM item;
61         const char *attr;
62         const char *value;
63         FR_TOKEN operator;
64         FR_TOKEN value_type;
65 };
66 struct conf_part {
67         CONF_ITEM item;
68         const char *name1;
69         const char *name2;
70         struct conf_item *children;
71         struct conf_item *tail; /* for speed */
72         CONF_SECTION    *template;
73         rbtree_t        *pair_tree; /* and a partridge.. */
74         rbtree_t        *section_tree; /* no jokes here */
75         rbtree_t        *name2_tree; /* for sections of the same name2 */
76         rbtree_t        *data_tree;
77         void            *base;
78         int depth;
79         const CONF_PARSER *variables;
80 };
81
82
83 /*
84  *      Internal data that is associated with a configuration section,
85  *      so that we don't have to track it separately.
86  */
87 struct conf_data {
88         CONF_ITEM  item;
89         const char *name;
90         int        flag;
91         void       *data;       /* user data */
92         void       (*free)(void *); /* free user data function */
93 };
94
95
96 static int cf_data_add_internal(CONF_SECTION *cs, const char *name,
97                                 void *data, void (*data_free)(void *),
98                                 int flag);
99 static void *cf_data_find_internal(CONF_SECTION *cs, const char *name,
100                                    int flag);
101
102 /*
103  *      Isolate the scary casts in these tiny provably-safe functions
104  */
105 CONF_PAIR *cf_itemtopair(CONF_ITEM *ci)
106 {
107         if (ci == NULL)
108                 return NULL;
109         rad_assert(ci->type == CONF_ITEM_PAIR);
110         return (CONF_PAIR *)ci;
111 }
112 CONF_SECTION *cf_itemtosection(CONF_ITEM *ci)
113 {
114         if (ci == NULL)
115                 return NULL;
116         rad_assert(ci->type == CONF_ITEM_SECTION);
117         return (CONF_SECTION *)ci;
118 }
119 CONF_ITEM *cf_pairtoitem(CONF_PAIR *cp)
120 {
121         if (cp == NULL)
122                 return NULL;
123         return (CONF_ITEM *)cp;
124 }
125 CONF_ITEM *cf_sectiontoitem(CONF_SECTION *cs)
126 {
127         if (cs == NULL)
128                 return NULL;
129         return (CONF_ITEM *)cs;
130 }
131
132 static CONF_DATA *cf_itemtodata(CONF_ITEM *ci)
133 {
134         if (ci == NULL)
135                 return NULL;
136         rad_assert(ci->type == CONF_ITEM_DATA);
137         return (CONF_DATA *)ci;
138 }
139 static CONF_ITEM *cf_datatoitem(CONF_DATA *cd)
140 {
141         if (cd == NULL)
142                 return NULL;
143         return (CONF_ITEM *)cd;
144 }
145
146 /*
147  *      Create a new CONF_PAIR
148  */
149 static CONF_PAIR *cf_pair_alloc(const char *attr, const char *value,
150                                 FR_TOKEN operator, FR_TOKEN value_type,
151                                 CONF_SECTION *parent)
152 {
153         char *p;
154         size_t attr_len, value_len = 0;
155         CONF_PAIR *cp;
156
157         if (!attr) return NULL;
158         attr_len = strlen(attr) + 1;
159         if (value) value_len = strlen(value) + 1;
160
161         p = rad_malloc(sizeof(*cp) + attr_len + value_len);
162
163         cp = (CONF_PAIR *) p;
164         memset(cp, 0, sizeof(*cp));
165         cp->item.type = CONF_ITEM_PAIR;
166         cp->item.parent = parent;
167
168         p += sizeof(*cp);
169         memcpy(p, attr, attr_len);
170         cp->attr = p;
171
172         if (value) {
173                 p += attr_len;
174                 memcpy(p, value, value_len);
175                 cp->value = p;
176         }
177         cp->value_type = value_type;
178         cp->operator = operator;
179
180         return cp;
181 }
182
183 /*
184  *      Free a CONF_PAIR
185  */
186 void cf_pair_free(CONF_PAIR **cp)
187 {
188         if (!cp || !*cp) return;
189
190         /*
191          *      attr && value are allocated contiguous with cp.
192          */
193
194 #ifndef NDEBUG
195         memset(*cp, 0, sizeof(*cp));
196 #endif
197         free(*cp);
198
199         *cp = NULL;
200 }
201
202
203 static void cf_data_free(CONF_DATA **cd)
204 {
205         if (!cd || !*cd) return;
206
207         /* name is allocated contiguous with cd */
208         if (!(*cd)->free) {
209                 free((*cd)->data);
210         } else {
211                 ((*cd)->free)((*cd)->data);
212         }
213 #ifndef NDEBUG
214         memset(*cd, 0, sizeof(*cd));
215 #endif
216         free(*cd);
217         *cd = NULL;
218 }
219
220 /*
221  *      rbtree callback function
222  */
223 static int pair_cmp(const void *a, const void *b)
224 {
225         const CONF_PAIR *one = a;
226         const CONF_PAIR *two = b;
227
228         return strcmp(one->attr, two->attr);
229 }
230
231
232 /*
233  *      rbtree callback function
234  */
235 static int section_cmp(const void *a, const void *b)
236 {
237         const CONF_SECTION *one = a;
238         const CONF_SECTION *two = b;
239
240         return strcmp(one->name1, two->name1);
241 }
242
243
244 /*
245  *      rbtree callback function
246  */
247 static int name2_cmp(const void *a, const void *b)
248 {
249         const CONF_SECTION *one = a;
250         const CONF_SECTION *two = b;
251
252         rad_assert(strcmp(one->name1, two->name1) == 0);
253
254         if (!one->name2 && !two->name2) return 0;
255         if (!one->name2) return -1;
256         if (!two->name2) return +1;
257
258         return strcmp(one->name2, two->name2);
259 }
260
261
262 /*
263  *      rbtree callback function
264  */
265 static int data_cmp(const void *a, const void *b)
266 {
267         int rcode;
268
269         const CONF_DATA *one = a;
270         const CONF_DATA *two = b;
271
272         rcode = one->flag - two->flag;
273         if (rcode != 0) return rcode;
274
275         return strcmp(one->name, two->name);
276 }
277
278
279 /*
280  *      Free strings we've parsed into data structures.
281  */
282 void cf_section_parse_free(CONF_SECTION *cs, void *base)
283 {
284         int i;
285         const CONF_PARSER *variables = cs->variables;
286
287         /*
288          *      Don't automatically free the strings if we're being
289          *      called from a module.  This is also for clients.c,
290          *      where client_free() expects to be able to free the
291          *      client structure.  If we moved everything to key off
292          *      of the config files, we might solve some problems...
293          */
294         if (!variables) return;
295
296         /*
297          *      Free up dynamically allocated string pointers.
298          */
299         for (i = 0; variables[i].name != NULL; i++) {
300                 char **p;
301
302                 if ((variables[i].type != PW_TYPE_STRING_PTR) &&
303                     (variables[i].type != PW_TYPE_FILENAME)) {
304                         continue;
305                 }
306
307                 /*
308                  *      No base struct offset, data must be the pointer.
309                  *      If data doesn't exist, ignore the entry, there
310                  *      must be something wrong.
311                  */
312                 if (!base) {
313                         if (!variables[i].data) {
314                                 continue;
315                         }
316
317                         p = (char **) variables[i].data;;
318
319                 } else if (variables[i].data) {
320                         p = (char **) variables[i].data;;
321
322                 } else {
323                         p = (char **) (((char *)base) + variables[i].offset);
324                 }
325
326                 free(*p);
327                 *p = NULL;
328         }
329 }
330
331
332 /*
333  *      Free a CONF_SECTION
334  */
335 void cf_section_free(CONF_SECTION **cs)
336 {
337         CONF_ITEM       *ci, *next;
338
339         if (!cs || !*cs) return;
340
341         cf_section_parse_free(*cs, (*cs)->base);
342
343         for (ci = (*cs)->children; ci; ci = next) {
344                 next = ci->next;
345
346                 switch (ci->type) {
347                 case CONF_ITEM_PAIR: {
348                                 CONF_PAIR *pair = cf_itemtopair(ci);
349                                 cf_pair_free(&pair);
350                         }
351                         break;
352
353                 case CONF_ITEM_SECTION: {
354                                 CONF_SECTION *section = cf_itemtosection(ci);
355                                 cf_section_free(&section);
356                         }
357                         break;
358
359                 case CONF_ITEM_DATA: {
360                                 CONF_DATA *data = cf_itemtodata(ci);
361                                 cf_data_free(&data);
362                         }
363                         break;
364
365                 default:        /* should really be an error. */
366                         break;
367                 }
368         }
369
370         /*
371          *      Name1 and name2 are allocated contiguous with
372          *      cs.
373          */
374         if ((*cs)->pair_tree)
375                 rbtree_free((*cs)->pair_tree);
376         if ((*cs)->section_tree)
377                 rbtree_free((*cs)->section_tree);
378         if ((*cs)->name2_tree)
379                 rbtree_free((*cs)->name2_tree);
380         if ((*cs)->data_tree)
381                 rbtree_free((*cs)->data_tree);
382
383         /*
384          * And free the section
385          */
386 #ifndef NDEBUG
387         memset(*cs, 0, sizeof(*cs));
388 #endif
389         free(*cs);
390
391         *cs = NULL;
392 }
393
394
395 /*
396  *      Allocate a CONF_SECTION
397  */
398 static CONF_SECTION *cf_section_alloc(const char *name1, const char *name2,
399                                       CONF_SECTION *parent)
400 {
401         size_t name1_len, name2_len = 0;
402         char *p;
403         CONF_SECTION    *cs;
404
405         if (!name1) return NULL;
406
407         name1_len = strlen(name1) + 1;
408         if (name2) name2_len = strlen(name2) + 1;
409
410         p = rad_malloc(sizeof(*cs) + name1_len + name2_len);
411
412         cs = (CONF_SECTION *) p;
413         memset(cs, 0, sizeof(*cs));
414         cs->item.type = CONF_ITEM_SECTION;
415         cs->item.parent = parent;
416
417         p += sizeof(*cs);
418         memcpy(p, name1, name1_len);
419         cs->name1 = p;
420
421         if (name2 && *name2) {
422                 p += name1_len;
423                 memcpy(p, name2, name2_len);
424                 cs->name2 = p;
425         }
426
427         cs->pair_tree = rbtree_create(pair_cmp, NULL, 0);
428         if (!cs->pair_tree) {
429                 cf_section_free(&cs);
430                 return NULL;
431         }
432
433         /*
434          *      Don't create a data tree, it may not be needed.
435          */
436
437         /*
438          *      Don't create the section tree here, it may not
439          *      be needed.
440          */
441
442         if (parent) cs->depth = parent->depth + 1;
443
444         return cs;
445 }
446
447
448 /*
449  *      Add an item to a configuration section.
450  */
451 static void cf_item_add(CONF_SECTION *cs, CONF_ITEM *ci)
452 {
453         if (!cs->children) {
454                 rad_assert(cs->tail == NULL);
455                 cs->children = ci;
456         } else {
457                 rad_assert(cs->tail != NULL);
458                 cs->tail->next = ci;
459         }
460
461         /*
462          *      Update the trees (and tail) for each item added.
463          */
464         for (/* nothing */; ci != NULL; ci = ci->next) {
465                 cs->tail = ci;
466
467                 /*
468                  *      For fast lookups, pair's and sections get
469                  *      added to rbtree's.
470                  */
471                 switch (ci->type) {
472                         case CONF_ITEM_PAIR:
473                                 rbtree_insert(cs->pair_tree, ci);
474                                 break;
475
476                         case CONF_ITEM_SECTION: {
477                                 CONF_SECTION *cs_new = cf_itemtosection(ci);
478
479                                 if (!cs->section_tree) {
480                                         cs->section_tree = rbtree_create(section_cmp, NULL, 0);
481                                         /* ignore any errors */
482                                 }
483
484                                 if (cs->section_tree) {
485                                         rbtree_insert(cs->section_tree, cs_new);                                }
486
487                                 /*
488                                  *      Two names: find the named instance.
489                                  */
490                                 {
491                                         CONF_SECTION *old_cs;
492
493                                         /*
494                                          *      Find the FIRST
495                                          *      CONF_SECTION having
496                                          *      the given name1, and
497                                          *      create a new tree
498                                          *      under it.
499                                          */
500                                         old_cs = rbtree_finddata(cs->section_tree, cs_new);
501                                         if (!old_cs) return; /* this is a bad error! */
502
503                                         if (!old_cs->name2_tree) {
504                                                 old_cs->name2_tree = rbtree_create(name2_cmp,
505                                                                                    NULL, 0);
506                                         }
507                                         if (old_cs->name2_tree) {
508                                                 rbtree_insert(old_cs->name2_tree, cs_new);
509                                         }
510                                 } /* had a name2 */
511                                 break;
512                         } /* was a section */
513
514                         case CONF_ITEM_DATA:
515                                 if (!cs->data_tree) {
516                                         cs->data_tree = rbtree_create(data_cmp, NULL, 0);
517                                 }
518                                 if (cs->data_tree) {
519                                         rbtree_insert(cs->data_tree, ci);
520                                 }
521                                 break;
522
523                         default: /* FIXME: assert & error! */
524                                 break;
525
526                 } /* switch over conf types */
527         } /* loop over ci */
528 }
529
530
531 CONF_ITEM *cf_reference_item(const CONF_SECTION *parentcs,
532                              CONF_SECTION *outercs,
533                              const char *ptr)
534 {
535         CONF_PAIR *cp;
536         CONF_SECTION *next;
537         const CONF_SECTION *cs = outercs;
538         char name[8192];
539         char *p;
540
541         strlcpy(name, ptr, sizeof(name));
542         p = name;
543
544         /*
545          *      ".foo" means "foo from the current section"
546          */
547         if (*p == '.') {
548                 p++;
549                 
550                 /*
551                  *      ..foo means "foo from the section
552                  *      enclosing this section" (etc.)
553                  */
554                 while (*p == '.') {
555                         if (cs->item.parent)
556                                 cs = cs->item.parent;
557                         p++;
558                 }
559
560                 /*
561                  *      "foo.bar.baz" means "from the root"
562                  */
563         } else if (strchr(p, '.') != NULL) {
564                 cs = parentcs;
565         }
566
567         while (*p) {
568                 char *q, *r;
569
570                 r = strchr(p, '[');
571                 q = strchr(p, '.');
572                 if (!r && !q) break;
573
574                 if (r && q > r) q = NULL;
575                 if (q && q < r) r = NULL;
576
577                 /*
578                  *      Split off name2.
579                  */
580                 if (r) {
581                         q = strchr(r + 1, ']');
582                         if (!q) return NULL; /* parse error */
583
584                         /*
585                          *      Points to foo[bar]xx: parse error,
586                          *      it should be foo[bar] or foo[bar].baz
587                          */
588                         if (q[1] && q[1] != '.') goto no_such_item;
589
590                         *r = '\0';
591                         *q = '\0';
592                         next = cf_section_sub_find_name2(cs, p, r + 1);
593                         *r = '[';
594                         *q = ']';
595
596                         /*
597                          *      Points to a named instance of a section.
598                          */
599                         if (!q[1]) {
600                                 if (!next) goto no_such_item;
601                                 return cf_sectiontoitem(next);
602                         }
603
604                         q++;    /* ensure we skip the ']' and '.' */
605
606                 } else {
607                         *q = '\0';
608                         next = cf_section_sub_find(cs, p);
609                         *q = '.';
610                 }
611
612                 if (!next) break; /* it MAY be a pair in this section! */
613
614                 cs = next;
615                 p = q + 1;
616         }
617
618         if (!*p) goto no_such_item;
619
620  retry:
621         /*
622          *      Find it in the current referenced
623          *      section.
624          */
625         cp = cf_pair_find(cs, p);
626         if (cp) return cf_pairtoitem(cp);
627
628         next = cf_section_sub_find(cs, p);
629         if (next) return cf_sectiontoitem(next);
630         
631         /*
632          *      "foo" is "in the current section, OR in main".
633          */
634         if ((p == name) && (cs != parentcs)) {
635                 cs = parentcs;
636                 goto retry;
637         }
638
639 no_such_item:
640         DEBUG2("WARNING: No such configuration item %s", ptr);
641         return NULL;
642 }
643
644
645 CONF_SECTION *cf_top_section(CONF_SECTION *cs)
646 {
647         while (cs->item.parent != NULL) {
648                 cs = cs->item.parent;
649         }
650
651         return cs;
652 }
653
654
655 /*
656  *      Expand the variables in an input string.
657  */
658 static const char *cf_expand_variables(const char *cf, int *lineno,
659                                        CONF_SECTION *outercs,
660                                        char *output, const char *input)
661 {
662         char *p;
663         const char *end, *ptr;
664         const CONF_SECTION *parentcs;
665         char name[8192];
666
667         /*
668          *      Find the master parent conf section.
669          *      We can't use mainconfig.config, because we're in the
670          *      process of re-building it, and it isn't set up yet...
671          */
672         parentcs = cf_top_section(outercs);
673
674         p = output;
675         ptr = input;
676         while (*ptr) {
677                 /*
678                  *      Ignore anything other than "${"
679                  */
680                 if ((*ptr == '$') && (ptr[1] == '{')) {
681                         CONF_ITEM *ci;
682                         CONF_PAIR *cp;
683
684                         /*
685                          *      FIXME: Add support for ${foo:-bar},
686                          *      like in xlat.c
687                          */
688
689                         /*
690                          *      Look for trailing '}', and log a
691                          *      warning for anything that doesn't match,
692                          *      and exit with a fatal error.
693                          */
694                         end = strchr(ptr, '}');
695                         if (end == NULL) {
696                                 *p = '\0';
697                                 radlog(L_INFO, "%s[%d]: Variable expansion missing }",
698                                        cf, *lineno);
699                                 return NULL;
700                         }
701
702                         ptr += 2;
703
704                         /*
705                          *      Can't really happen because input lines are
706                          *      capped at 8k, which is sizeof(name)
707                          */
708                         if ((size_t) (end - ptr) >= sizeof(name)) {
709                                 radlog(L_ERR, "%s[%d]: Reference string is too large",
710                                        cf, *lineno);
711                                 return NULL;
712                         }
713
714                         memcpy(name, ptr, end - ptr);
715                         name[end - ptr] = '\0';
716
717                         ci = cf_reference_item(parentcs, outercs, name);
718                         if (!ci || (ci->type != CONF_ITEM_PAIR)) {
719                                 radlog(L_ERR, "%s[%d]: Reference \"%s\" not found",
720                                        cf, *lineno, input);
721                                 return NULL;
722                         }
723
724                         /*
725                          *  Substitute the value of the variable.
726                          */
727                         cp = cf_itemtopair(ci);
728                         strcpy(p, cp->value);
729                         p += strlen(p);
730                         ptr = end + 1;
731
732                 } else if (memcmp(ptr, "$ENV{", 5) == 0) {
733                         char *env;
734
735                         ptr += 5;
736
737                         /*
738                          *      Look for trailing '}', and log a
739                          *      warning for anything that doesn't match,
740                          *      and exit with a fatal error.
741                          */
742                         end = strchr(ptr, '}');
743                         if (end == NULL) {
744                                 *p = '\0';
745                                 radlog(L_INFO, "%s[%d]: Environment variable expansion missing }",
746                                        cf, *lineno);
747                                 return NULL;
748                         }
749
750                         /*
751                          *      Can't really happen because input lines are
752                          *      capped at 8k, which is sizeof(name)
753                          */
754                         if ((size_t) (end - ptr) >= sizeof(name)) {
755                                 radlog(L_ERR, "%s[%d]: Environment variable name is too large",
756                                        cf, *lineno);
757                                 return NULL;
758                         }
759
760                         memcpy(name, ptr, end - ptr);
761                         name[end - ptr] = '\0';
762
763                         /*
764                          *      Get the environment variable.
765                          *      If none exists, then make it an empty string.
766                          */
767                         env = getenv(name);
768                         if (env == NULL) {
769                                 *name = '\0';
770                                 env = name;
771                         }
772
773                         strcpy(p, env);
774                         p += strlen(p);
775                         ptr = end + 1;
776
777                 } else {
778                         /*
779                          *      Copy it over verbatim.
780                          */
781                         *(p++) = *(ptr++);
782                 }
783         } /* loop over all of the input string. */
784
785         *p = '\0';
786
787         return output;
788 }
789
790
791 /*
792  *      Parses an item (not a CONF_ITEM) into the specified format,
793  *      with a default value.
794  *
795  *      Returns -1 on error, 0 for correctly parsed, and 1 if the
796  *      default value was used.  Note that the default value will be
797  *      used ONLY if the CONF_PAIR is NULL.
798  */
799 int cf_item_parse(CONF_SECTION *cs, const char *name,
800                   int type, void *data, const char *dflt)
801 {
802         int rcode = 0;
803         char **q;
804         const char *value;
805         fr_ipaddr_t ipaddr;
806         const CONF_PAIR *cp;
807         char ipbuf[128];
808
809         cp = cf_pair_find(cs, name);
810         if (cp) {
811                 value = cp->value;
812
813         } else if (!dflt) {
814                 return 1;       /* nothing to parse, return default value */
815
816         } else {
817                 rcode = 1;
818                 value = dflt;
819         }
820
821         if (!value) {
822                 return 0;
823         }
824
825         switch (type) {
826         case PW_TYPE_BOOLEAN:
827                 /*
828                  *      Allow yes/no and on/off
829                  */
830                 if ((strcasecmp(value, "yes") == 0) ||
831                     (strcasecmp(value, "on") == 0)) {
832                         *(int *)data = 1;
833                 } else if ((strcasecmp(value, "no") == 0) ||
834                            (strcasecmp(value, "off") == 0)) {
835                         *(int *)data = 0;
836                 } else {
837                         *(int *)data = 0;
838                         radlog(L_ERR, "Bad value \"%s\" for boolean variable %s", value, name);
839                         return -1;
840                 }
841                 DEBUG2("\t%s = %s", name, value);
842                 break;
843
844         case PW_TYPE_INTEGER:
845                 *(int *)data = strtol(value, 0, 0);
846                 DEBUG2("\t%s = %d", name, *(int *)data);
847                 break;
848
849         case PW_TYPE_STRING_PTR:
850                 q = (char **) data;
851                 if (*q != NULL) {
852                         free(*q);
853                 }
854
855                 /*
856                  *      Expand variables which haven't already been
857                  *      expanded automagically when the configuration
858                  *      file was read.
859                  */
860                 if (value == dflt) {
861                         char buffer[8192];
862
863                         int lineno = cs->item.lineno;
864
865                         /*
866                          *      FIXME: sizeof(buffer)?
867                          */
868                         value = cf_expand_variables("?",
869                                                     &lineno,
870                                                     cs, buffer, value);
871                         if (!value) return -1;
872                 }
873
874                 DEBUG2("\t%s = \"%s\"", name, value ? value : "(null)");
875                 *q = value ? strdup(value) : NULL;
876                 break;
877
878                 /*
879                  *      This is the same as PW_TYPE_STRING_PTR,
880                  *      except that we also "stat" the file, and
881                  *      cache the result.
882                  */
883         case PW_TYPE_FILENAME:
884                 q = (char **) data;
885                 if (*q != NULL) {
886                         free(*q);
887                 }
888
889                 /*
890                  *      Expand variables which haven't already been
891                  *      expanded automagically when the configuration
892                  *      file was read.
893                  */
894                 if (value == dflt) {
895                         char buffer[8192];
896
897                         int lineno = cs->item.lineno;
898
899                         /*
900                          *      FIXME: sizeof(buffer)?
901                          */
902                         value = cf_expand_variables("?",
903                                                     &lineno,
904                                                     cs, buffer, value);
905                         if (!value) return -1;
906                 }
907
908                 DEBUG2("\t%s = \"%s\"", name, value ? value : "(null)");
909                 *q = value ? strdup(value) : NULL;
910
911                 /*
912                  *      And now we "stat" the file.
913                  */
914                 if (*q) {
915                         struct stat buf;
916
917                         if (stat(*q, &buf) == 0) {
918                                 time_t *mtime;
919
920                                 mtime = rad_malloc(sizeof(*mtime));
921                                 *mtime = buf.st_mtime;
922                                 /* FIXME: error? */
923                                 cf_data_add_internal(cs, *q, mtime, free,
924                                                      PW_TYPE_FILENAME);
925                         }
926                 }
927                 break;
928
929         case PW_TYPE_IPADDR:
930                 /*
931                  *      Allow '*' as any address
932                  */
933                 if (strcmp(value, "*") == 0) {
934                         *(uint32_t *) data = htonl(INADDR_ANY);
935                         DEBUG2("\t%s = *", name);
936                         break;
937                 }
938                 if (ip_hton(value, AF_INET, &ipaddr) < 0) {
939                         radlog(L_ERR, "Can't find IP address for host %s", value);
940                         return -1;
941                 }
942                 
943                 if (strspn(value, "0123456789.") == strlen(value)) {
944                         DEBUG2("\t%s = %s", name, value);
945                 } else {
946                         DEBUG2("\t%s = %s IP address [%s]", name, value,
947                                ip_ntoh(&ipaddr, ipbuf, sizeof(ipbuf)));
948                 }
949                 *(uint32_t *) data = ipaddr.ipaddr.ip4addr.s_addr;
950                 break;
951
952         case PW_TYPE_IPV6ADDR:
953                 if (ip_hton(value, AF_INET6, &ipaddr) < 0) {
954                         radlog(L_ERR, "Can't find IPv6 address for host %s", value);
955                         return -1;
956                 }
957                 DEBUG2("\t%s = %s IPv6 address [%s]", name, value,
958                                ip_ntoh(&ipaddr, ipbuf, sizeof(ipbuf)));
959                 memcpy(data, &ipaddr.ipaddr.ip6addr,
960                        sizeof(ipaddr.ipaddr.ip6addr));
961                 break;
962
963         default:
964                 radlog(L_ERR, "type %d not supported yet", type);
965                 return -1;
966                 break;
967         } /* switch over variable type */
968
969         return rcode;
970 }
971
972 static const char *parse_spaces = "                                                                                                                                                                                                                                                                ";
973
974 /*
975  *      Parse a configuration section into user-supplied variables.
976  */
977 int cf_section_parse(CONF_SECTION *cs, void *base,
978                      const CONF_PARSER *variables)
979 {
980         int i;
981         void *data;
982
983         cs->variables = variables; /* this doesn't hurt anything */
984
985         if (!cs->name2) {
986                 DEBUG2("%.*s%s {", cs->depth, parse_spaces,
987                        cs->name1);
988         } else {
989                 DEBUG2("%.*s%s %s {", cs->depth, parse_spaces,
990                        cs->name1, cs->name2);
991         }
992
993         /*
994          *      Handle the known configuration parameters.
995          */
996         for (i = 0; variables[i].name != NULL; i++) {
997                 /*
998                  *      Handle subsections specially
999                  */
1000                 if (variables[i].type == PW_TYPE_SUBSECTION) {
1001                         CONF_SECTION *subcs;
1002                         subcs = cf_section_sub_find(cs, variables[i].name);
1003
1004                         /*
1005                          *      If the configuration section is NOT there,
1006                          *      then ignore it.
1007                          *
1008                          *      FIXME! This is probably wrong... we should
1009                          *      probably set the items to their default values.
1010                          */
1011                         if (!subcs) continue;
1012
1013                         if (!variables[i].dflt) {
1014                                 DEBUG2("Internal sanity check 1 failed in cf_section_parse");
1015                                 goto error;
1016                         }
1017
1018                         if (cf_section_parse(subcs, base,
1019                                              (const CONF_PARSER *) variables[i].dflt) < 0) {
1020                                 goto error;
1021                         }
1022                         continue;
1023                 } /* else it's a CONF_PAIR */
1024
1025                 if (variables[i].data) {
1026                         data = variables[i].data; /* prefer this. */
1027                 } else if (base) {
1028                         data = ((char *)base) + variables[i].offset;
1029                 } else {
1030                         DEBUG2("Internal sanity check 2 failed in cf_section_parse");
1031                         goto error;
1032                 }
1033
1034                 /*
1035                  *      Parse the pair we found, or a default value.
1036                  */
1037                 if (cf_item_parse(cs, variables[i].name, variables[i].type,
1038                                   data, variables[i].dflt) < 0) {
1039                         goto error;
1040                 }
1041         } /* for all variables in the configuration section */
1042
1043         DEBUG2("%.*s}", cs->depth, parse_spaces);
1044
1045         cs->base = base;
1046
1047         return 0;
1048
1049  error:
1050         DEBUG2("%.*s}", cs->depth, parse_spaces);
1051         cf_section_parse_free(cs, base);
1052         return -1;
1053 }
1054
1055
1056 /*
1057  *      Sanity check the "if" or "elsif", presuming that the first '('
1058  *      has already been eaten.
1059  *
1060  *      We're not really parsing it here, just checking if it's mostly
1061  *      well-formed.
1062  */
1063 static int condition_looks_ok(char **ptr)
1064 {
1065         int num_braces = 1;
1066         int quote = 0;
1067         char *p = *ptr;
1068
1069         while (*p) {
1070                 if (quote) {
1071                         if (*p == quote) {
1072                                 p++;
1073                                 quote = 0;
1074                                 continue;
1075                         }
1076
1077                         if (*p == '\\') {
1078                                 if (!p[1]) {
1079                                         return 0; /* no trailing slash */
1080                                 }
1081                                 p += 2;
1082                                 continue;
1083                         }
1084                         p++;
1085                         continue;
1086                 }
1087
1088                 switch (*p) {
1089                 case '\\':
1090                         if (!p[1]) {
1091                                 return 0; /* no trailing slash */
1092                         }
1093                         p += 2;
1094                         continue;
1095
1096                 case '(':
1097                         num_braces++;
1098                         p++;
1099                         continue;
1100
1101                 case ')':
1102                         if (num_braces == 1) {
1103                                 const char *q = p + 1;
1104
1105                                 /*
1106                                  *      Validate that there isn't much
1107                                  *      else after the closing brace.
1108                                  */
1109                                 while ((*q == ' ') || (*q == '\t')) q++;
1110
1111                                 /*
1112                                  *      Parse error.
1113                                  */
1114                                 if (*q != '{') {
1115                                         return 0;
1116                                 }
1117
1118                                 *ptr = p + 1; /* include the trailing ')' */
1119                                 return 1;
1120                         }
1121                         num_braces--;
1122                         p++;
1123                         continue;
1124
1125                 case '"':
1126                 case '\'':
1127                 case '/':
1128                 case '`':
1129                         quote = *p;
1130                         /* FALL-THROUGH */
1131
1132                 default:
1133                         p++;
1134                         break;
1135                 }
1136         }
1137
1138         return 0;
1139 }
1140
1141
1142 static const char *cf_local_file(CONF_SECTION *cs, const char *local,
1143                                  char *buffer, size_t bufsize)
1144 {
1145         size_t dirsize;
1146         const char *p;
1147         CONF_SECTION *parentcs = cf_top_section(cs);
1148
1149         p = strrchr(parentcs->item.filename, FR_DIR_SEP);
1150         if (!p) return local;
1151
1152         dirsize = (p - parentcs->item.filename) + 1;
1153
1154         if ((dirsize + strlen(local)) >= bufsize) {
1155                 return NULL;
1156         }
1157
1158         memcpy(buffer, parentcs->item.filename, dirsize);
1159         strlcpy(buffer + dirsize, local, bufsize - dirsize);
1160
1161         return buffer;
1162 }
1163
1164
1165 /*
1166  *      Read a part of the config file.
1167  */
1168 static int cf_section_read(const char *filename, int *lineno, FILE *fp,
1169                            CONF_SECTION *current)
1170
1171 {
1172         CONF_SECTION *this, *css;
1173         CONF_PAIR *cpn;
1174         char *ptr;
1175         const char *value;
1176         char buf[8192];
1177         char buf1[8192];
1178         char buf2[8192];
1179         char buf3[8192];
1180         int t1, t2, t3;
1181         char *cbuf = buf;
1182         size_t len;
1183
1184         this = current;         /* add items here */
1185
1186         /*
1187          *      Read, checking for line continuations ('\\' at EOL)
1188          */
1189         for (;;) {
1190                 int eof;
1191
1192                 /*
1193                  *      Get data, and remember if we are at EOF.
1194                  */
1195                 eof = (fgets(cbuf, sizeof(buf) - (cbuf - buf), fp) == NULL);
1196                 (*lineno)++;
1197
1198                 len = strlen(cbuf);
1199
1200                 /*
1201                  *      We've filled the buffer, and there isn't
1202                  *      a CR in it.  Die!
1203                  */
1204                 if ((cbuf[len - 1] != '\n') && !feof(fp)) {
1205                         radlog(L_ERR, "%s[%d]: Line too long",
1206                                filename, *lineno);
1207                         return -1;
1208                 }
1209
1210                 /*
1211                  *  Check for continuations.
1212                  */
1213                 if (cbuf[len - 1] == '\n') len--;
1214
1215                 /*
1216                  *      Last character is '\\'.  Over-write it,
1217                  *      and read another line.
1218                  */
1219                 if ((len > 0) && (cbuf[len - 1] == '\\')) {
1220                         if (len >= (sizeof(buf) - 5)) {
1221                                 radlog(L_ERR, "%s[%d]: Line too long",
1222                                        filename, *lineno);
1223                                 return -1;
1224                         }
1225
1226                         cbuf[len - 1] = '\0';
1227                         cbuf += len - 1;
1228                         continue;
1229                 }
1230
1231                 /*
1232                  *  We're at EOF, and haven't read anything.  Stop.
1233                  */
1234                 if (eof && (cbuf == buf)) {
1235                         break;
1236                 }
1237
1238                 ptr = cbuf = buf;
1239                 t1 = gettoken(&ptr, buf1, sizeof(buf1));
1240
1241                 if ((*buf1 == '#') || (*buf1 == '\0')) {
1242                         continue;
1243                 }
1244
1245                 /*
1246                  *      The caller eats "name1 name2 {", and calls us
1247                  *      for the data inside of the section.  So if we
1248                  *      receive a closing brace, then it must mean the
1249                  *      end of the section.
1250                  */
1251                if (t1 == T_RCBRACE) {
1252                        if (this == current) {
1253                                radlog(L_ERR, "%s[%d]: Too many closing braces",
1254                                       filename, *lineno);
1255                                return -1;
1256
1257                        }
1258                        this = this->item.parent;
1259                        continue;
1260                 }
1261
1262                 /*
1263                  *      Allow for $INCLUDE files
1264                  *
1265                  *      This *SHOULD* work for any level include.
1266                  *      I really really really hate this file.  -cparker
1267                  */
1268                if ((strcasecmp(buf1, "$INCLUDE") == 0) ||
1269                    (strcasecmp(buf1, "$-INCLUDE") == 0)) {
1270                        int relative = 1;
1271
1272                         t2 = getword(&ptr, buf2, sizeof(buf2));
1273
1274                         if (buf2[0] == '$') relative = 0;
1275
1276                         value = cf_expand_variables(filename, lineno, this, buf, buf2);
1277                         if (!value) return -1;
1278
1279                         if (!FR_DIR_IS_RELATIVE(value)) relative = 0;
1280
1281                         if (relative) {
1282                                 value = cf_local_file(current, value, buf3,
1283                                                       sizeof(buf3));
1284                                 if (!value) {
1285                                         radlog(L_ERR, "%s[%d]: Directories too deep.",
1286                                                filename, *lineno);
1287                                         return -1;
1288                                 }
1289                         }
1290
1291
1292 #ifdef HAVE_DIRENT_H
1293                         /*
1294                          *      $INCLUDE foo/
1295                          *
1296                          *      Include ALL non-"dot" files in the directory.
1297                          *      careful!
1298                          */
1299                         if (value[strlen(value) - 1] == '/') {
1300                                 DIR             *dir;
1301                                 struct dirent   *dp;
1302                                 struct stat stat_buf;
1303
1304                                 DEBUG2("including files in directory %s", value );
1305                                 dir = opendir(value);
1306                                 if (!dir) {
1307                                         radlog(L_ERR, "%s[%d]: Error reading directory %s: %s",
1308                                                filename, *lineno, value,
1309                                                strerror(errno));
1310                                         return -1;
1311                                 }
1312
1313                                 /*
1314                                  *      Read the directory, ignoring "." files.
1315                                  */
1316                                 while ((dp = readdir(dir)) != NULL) {
1317                                         const char *p;
1318
1319                                         if (dp->d_name[0] == '.') continue;
1320
1321                                         /*
1322                                          *      Check for valid characters
1323                                          */
1324                                         for (p = dp->d_name; *p != '\0'; p++) {
1325                                                 if (isalpha((int)*p) ||
1326                                                     isdigit((int)*p) ||
1327                                                     (*p == '-') ||
1328                                                     (*p == '_') ||
1329                                                     (*p == '.')) continue;
1330                                                 break;
1331                                         }
1332                                         if (*p != '\0') continue;
1333
1334                                         snprintf(buf2, sizeof(buf2), "%s%s",
1335                                                  value, dp->d_name);
1336                                         if ((stat(buf2, &stat_buf) != 0) ||
1337                                             S_ISDIR(stat_buf.st_mode)) continue;
1338                                         /*
1339                                          *      Read the file into the current
1340                                          *      configuration sectoin.
1341                                          */
1342                                         if (cf_file_include(buf2, this) < 0) {
1343                                                 closedir(dir);
1344                                                 return -1;
1345                                         }
1346                                 }
1347                                 closedir(dir);
1348                         }  else
1349 #endif
1350                         { /* it was a normal file */
1351                                 if (buf1[1] == '-') {
1352                                         struct stat statbuf;
1353
1354                                         if (stat(value, &statbuf) < 0) {
1355                                                 DEBUG("WARNING: Not including file %s: %s", value, strerror(errno));
1356                                                 continue;
1357                                         }
1358                                 }
1359
1360                                 if (cf_file_include(value, this) < 0) {
1361                                         return -1;
1362                                 }
1363                         }
1364                         continue;
1365                 } /* we were in an include */
1366
1367                if (strcasecmp(buf1, "$template") == 0) {
1368                        CONF_ITEM *ci;
1369                        CONF_SECTION *parentcs;
1370                        t2 = getword(&ptr, buf2, sizeof(buf2));
1371
1372                        parentcs = cf_top_section(current);
1373
1374                        ci = cf_reference_item(parentcs, this, buf2);
1375                        if (!ci || (ci->type != CONF_ITEM_SECTION)) {
1376                                 radlog(L_ERR, "%s[%d]: Reference \"%s\" not found",
1377                                        filename, *lineno, buf2);
1378                                 return -1;
1379                        }
1380                        
1381                        if (this->template) {
1382                                 radlog(L_ERR, "%s[%d]: Section already has a template",
1383                                        filename, *lineno);
1384                                 return -1;
1385                        }
1386
1387                        this->template = cf_itemtosection(ci);
1388                        continue;
1389                }
1390
1391                 /*
1392                  *      Ensure that the user can't add CONF_PAIRs
1393                  *      with 'internal' names;
1394                  */
1395                 if (buf1[0] == '_') {
1396                         radlog(L_ERR, "%s[%d]: Illegal configuration pair name \"%s\"",
1397                                         filename, *lineno, buf1);
1398                         return -1;
1399                 }
1400
1401                 /*
1402                  *      Grab the next token.
1403                  */
1404                 t2 = gettoken(&ptr, buf2, sizeof(buf2));
1405                 switch (t2) {
1406                 case T_EOL:
1407                 case T_HASH:
1408                         t2 = T_OP_EQ;
1409                         value = NULL;
1410                         goto do_set;
1411
1412                 case T_OP_ADD:
1413                 case T_OP_CMP_EQ:
1414                 case T_OP_SUB:
1415                 case T_OP_LE:
1416                 case T_OP_GE:
1417                         if (!this || (strcmp(this->name1, "update") != 0)) {
1418                                 radlog(L_ERR, "%s[%d]: Invalid operator in assignment",
1419                                        filename, *lineno);
1420                                 return -1;
1421                         }
1422
1423                 case T_OP_EQ:
1424                 case T_OP_SET:
1425                 do_set:
1426                         t3 = getstring(&ptr, buf3, sizeof(buf3));
1427
1428                         /*
1429                          *      Handle variable substitution via ${foo}
1430                          */
1431                         if ((t3 == T_BARE_WORD) ||
1432                             (t3 == T_DOUBLE_QUOTED_STRING)) {
1433                                 value = cf_expand_variables(filename, lineno, this,
1434                                                             buf, buf3);
1435                                 if (!value) return -1;
1436                         } else if ((t3 == T_EOL) ||
1437                                    (t3 == T_HASH)) {
1438                                 value = NULL;
1439                         } else {
1440                                 value = buf3;
1441                         }
1442                         
1443                         /*
1444                          *      Add this CONF_PAIR to our CONF_SECTION
1445                          */
1446                         cpn = cf_pair_alloc(buf1, value, t2, t3, this);
1447                         cpn->item.filename = filename;
1448                         cpn->item.lineno = *lineno;
1449                         cf_item_add(this, cf_pairtoitem(cpn));
1450                         continue;
1451
1452                         /*
1453                          *      This horrible code is here to support
1454                          *      if/then/else failover in the
1455                          *      authorize, etc. sections.  It makes no
1456                          *      sense anywhere else.
1457                          */
1458                 case T_LBRACE:
1459                         if ((strcmp(buf1, "if") == 0) ||
1460                             (strcmp(buf1, "elsif") == 0)) {
1461                                 char *end = ptr;
1462                                 CONF_SECTION *server;
1463
1464                                 if (!condition_looks_ok(&end)) {
1465                                         radlog(L_ERR, "%s[%d]: Parse error in condition at: %s",
1466                                                filename, *lineno, ptr);
1467                                         return -1;
1468                                 }
1469
1470                                 if ((size_t) (end - ptr) >= (sizeof(buf2) - 1)) {
1471                                         radlog(L_ERR, "%s[%d]: Statement too complicated after \"%s\"",
1472                                                filename, *lineno, buf1);
1473                                         return -1;
1474                                 }
1475
1476                                 /*
1477                                  *      More sanity checking.  This is
1478                                  *      getting to be a horrible hack.
1479                                  */
1480                                 server = this;
1481                                 while (server) {
1482                                         if (strcmp(server->name1, "server") == 0) break;
1483                                         server = server->item.parent;
1484                                 }
1485                                 
1486                                 if (0 && !server) {
1487                                         radlog(L_ERR, "%s[%d]: Processing directives such as \"%s\" cannot be used here.",
1488                                                filename, *lineno, buf1);
1489                                         return -1;
1490                                 }
1491
1492                                 buf2[0] = '(';
1493                                 memcpy(buf2 + 1, ptr, end - ptr);
1494                                 buf2[end - ptr + 1] = '\0';
1495                                 ptr = end + 1;
1496                                 t2 = T_BARE_WORD;
1497                                 goto section_alloc;
1498
1499                         } else {
1500                                 radlog(L_ERR, "%s[%d]: Parse error after \"%s\"",
1501                                        filename, *lineno, buf1);
1502                                 return -1;
1503                         }
1504
1505                         /* FALL-THROUGH */
1506
1507                         /*
1508                          *      No '=', must be a section or sub-section.
1509                          */
1510                 case T_BARE_WORD:
1511                 case T_DOUBLE_QUOTED_STRING:
1512                 case T_SINGLE_QUOTED_STRING:
1513                         t3 = gettoken(&ptr, buf3, sizeof(buf3));
1514                         if (t3 != T_LCBRACE) {
1515                                 radlog(L_ERR, "%s[%d]: Expecting section start brace '{' after \"%s %s\"",
1516                                        filename, *lineno, buf1, buf2);
1517                                 return -1;
1518                         }
1519
1520                 case T_LCBRACE:
1521                 section_alloc:
1522                         css = cf_section_alloc(buf1,
1523                                                t2 == T_LCBRACE ? NULL : buf2,
1524                                                this);
1525                         if (!css) {
1526                                 radlog(L_ERR, "%s[%d]: Failed allocating memory for section",
1527                                                 filename, *lineno);
1528                                 return -1;
1529                         }
1530                         cf_item_add(this, cf_sectiontoitem(css));
1531                         css->item.filename = filename;
1532                         css->item.lineno = *lineno;
1533
1534                         /*
1535                          *      The current section is now the child section.
1536                          */
1537                         this = css;
1538                         continue;
1539
1540                 default:
1541                         radlog(L_ERR, "%s[%d]: Parse error after \"%s\"",
1542                                filename, *lineno, buf1);
1543                         return -1;
1544                 }
1545         }
1546
1547         /*
1548          *      See if EOF was unexpected ..
1549          */
1550         if (feof(fp) && (this != current)) {
1551                 radlog(L_ERR, "%s[%d]: EOF reached without closing brace for section %s starting at line %d",
1552                        filename, *lineno,
1553                        cf_section_name1(this), cf_section_lineno(this));
1554                 return -1;
1555         }
1556
1557         return 0;
1558 }
1559
1560 /*
1561  *      Include one config file in another.
1562  */
1563 int cf_file_include(const char *filename, CONF_SECTION *cs)
1564 {
1565         FILE            *fp;
1566         int             lineno = 0;
1567         struct stat     statbuf;
1568         time_t          *mtime;
1569         CONF_DATA       *cd;
1570
1571         DEBUG2( "including configuration file %s", filename);
1572
1573         if (stat(filename, &statbuf) == 0) {
1574 #ifdef S_IWOTH
1575                 if ((statbuf.st_mode & S_IWOTH) != 0) {
1576                         radlog(L_ERR|L_CONS, "Configuration file %s is globally writable.  Refusing to start due to insecure configuration.",
1577                                filename);
1578                         return -1;
1579                 }
1580 #endif
1581
1582 #ifdef S_IROTH
1583                 if (0 && (statbuf.st_mode & S_IROTH) != 0) {
1584                         radlog(L_ERR|L_CONS, "Configuration file %s is globally readable.  Refusing to start due to insecure configuration.",
1585                                filename);
1586                         return -1;
1587                 }
1588 #endif
1589         }
1590
1591         fp = fopen(filename, "r");
1592         if (!fp) {
1593                 radlog(L_ERR|L_CONS, "Unable to open file \"%s\": %s",
1594                        filename, strerror(errno));
1595                 return -1;
1596         }
1597
1598         /*
1599          *      Add the filename to the section
1600          */
1601         mtime = rad_malloc(sizeof(*mtime));
1602         *mtime = statbuf.st_mtime;
1603
1604         if (cf_data_add_internal(cs, filename, mtime, free,
1605                                  PW_TYPE_FILENAME) < 0) {
1606                 radlog(L_ERR|L_CONS, "Internal error open file \"%s\"",
1607                        filename);
1608                 return -1;
1609         }
1610
1611         cd = cf_data_find_internal(cs, filename, PW_TYPE_FILENAME);
1612         if (!cd) {
1613                 radlog(L_ERR|L_CONS, "Internal error open file \"%s\"",
1614                        filename);
1615                 return -1;
1616         }
1617
1618         if (!cs->item.filename) cs->item.filename = filename;
1619
1620         /*
1621          *      Read the section.  It's OK to have EOF without a
1622          *      matching close brace.
1623          */
1624         if (cf_section_read(cd->name, &lineno, fp, cs) < 0) {
1625                 fclose(fp);
1626                 return -1;
1627         }
1628
1629         fclose(fp);
1630         return 0;
1631 }
1632
1633 /*
1634  *      Bootstrap a config file.
1635  */
1636 CONF_SECTION *cf_file_read(const char *filename)
1637 {
1638         char *p;
1639         CONF_PAIR *cp;
1640         CONF_SECTION *cs;
1641
1642         cs = cf_section_alloc("main", NULL, NULL);
1643         if (!cs) return NULL;
1644
1645         cp = cf_pair_alloc("confdir", filename, T_OP_SET, T_BARE_WORD, cs);
1646         if (!cp) return NULL;
1647
1648         p = strrchr(cp->value, FR_DIR_SEP);
1649         if (p) *p = '\0';
1650
1651         cp->item.filename = "internal";
1652         cp->item.lineno = 0;
1653         cf_item_add(cs, cf_pairtoitem(cp));
1654
1655         if (cf_file_include(filename, cs) < 0) {
1656                 cf_section_free(&cs);
1657                 return NULL;
1658         }
1659
1660         return cs;
1661 }
1662
1663 /*
1664  * Return a CONF_PAIR within a CONF_SECTION.
1665  */
1666 CONF_PAIR *cf_pair_find(const CONF_SECTION *cs, const char *name)
1667 {
1668         CONF_ITEM       *ci;
1669         CONF_PAIR       *cp = NULL;
1670
1671         if (!cs) return NULL;
1672
1673         /*
1674          *      Find the name in the tree, for speed.
1675          */
1676         if (name) {
1677                 CONF_PAIR mycp;
1678
1679                 mycp.attr = name;
1680                 cp = rbtree_finddata(cs->pair_tree, &mycp);
1681         } else {
1682                 /*
1683                  *      Else find the first one that matches
1684                  */
1685                 for (ci = cs->children; ci; ci = ci->next) {
1686                         if (ci->type == CONF_ITEM_PAIR) {
1687                                 return cf_itemtopair(ci);
1688                         }
1689                 }
1690         }
1691
1692         if (cp || !cs->template) return cp;
1693
1694         return cf_pair_find(cs->template, name);
1695 }
1696
1697 /*
1698  * Return the attr of a CONF_PAIR
1699  */
1700
1701 const char *cf_pair_attr(CONF_PAIR *pair)
1702 {
1703         return (pair ? pair->attr : NULL);
1704 }
1705
1706 /*
1707  * Return the value of a CONF_PAIR
1708  */
1709
1710 const char *cf_pair_value(CONF_PAIR *pair)
1711 {
1712         return (pair ? pair->value : NULL);
1713 }
1714
1715 /*
1716  *      Copied here for error reporting.
1717  */
1718 extern void librad_log(const char *, ...);
1719
1720 /*
1721  * Turn a CONF_PAIR into a VALUE_PAIR
1722  * For now, ignore the "value_type" field...
1723  */
1724 VALUE_PAIR *cf_pairtovp(CONF_PAIR *pair)
1725 {
1726         DICT_ATTR *da;
1727         VALUE_PAIR *vp;
1728
1729         if (!pair) {
1730                 librad_log("Internal error");
1731                 return NULL;
1732         }
1733
1734         da = dict_attrbyname(pair->attr);
1735         if (!da) {
1736                 librad_log("Unknown attribute %s", pair->attr);
1737                 return NULL;
1738         }
1739
1740         if (!pair->value) {
1741                 librad_log("No value given for attribute %s", pair->attr);
1742                 return NULL;
1743         }
1744
1745         vp = pairalloc(da);
1746         if (!vp) {
1747                 librad_log("Out of memory");
1748                 return NULL;
1749         }
1750
1751         vp->operator = pair->operator;
1752
1753         if ((pair->value_type == T_BARE_WORD) ||
1754             (pair->value_type == T_SINGLE_QUOTED_STRING)) {
1755                 if (!pairparsevalue(vp, pair->value)) {
1756                         pairfree(&vp);
1757                         return NULL;
1758                 }
1759                 vp->flags.do_xlat = 0;
1760         } else {
1761                 vp->flags.do_xlat = 1;
1762         }
1763
1764         return vp;
1765 }
1766
1767 /*
1768  * Return the first label of a CONF_SECTION
1769  */
1770
1771 const char *cf_section_name1(const CONF_SECTION *cs)
1772 {
1773         return (cs ? cs->name1 : NULL);
1774 }
1775
1776 /*
1777  * Return the second label of a CONF_SECTION
1778  */
1779
1780 const char *cf_section_name2(const CONF_SECTION *cs)
1781 {
1782         return (cs ? cs->name2 : NULL);
1783 }
1784
1785 /*
1786  * Find a value in a CONF_SECTION
1787  */
1788 const char *cf_section_value_find(const CONF_SECTION *cs, const char *attr)
1789 {
1790         CONF_PAIR       *cp;
1791
1792         cp = cf_pair_find(cs, attr);
1793
1794         return (cp ? cp->value : NULL);
1795 }
1796
1797 /*
1798  * Return the next pair after a CONF_PAIR
1799  * with a certain name (char *attr) If the requested
1800  * attr is NULL, any attr matches.
1801  */
1802
1803 CONF_PAIR *cf_pair_find_next(const CONF_SECTION *cs,
1804                              CONF_PAIR *pair, const char *attr)
1805 {
1806         CONF_ITEM       *ci;
1807
1808         /*
1809          * If pair is NULL this must be a first time run
1810          * Find the pair with correct name
1811          */
1812
1813         if (pair == NULL){
1814                 return cf_pair_find(cs, attr);
1815         }
1816
1817         ci = cf_pairtoitem(pair)->next;
1818
1819         for (; ci; ci = ci->next) {
1820                 if (ci->type != CONF_ITEM_PAIR)
1821                         continue;
1822                 if (attr == NULL || strcmp(cf_itemtopair(ci)->attr, attr) == 0)
1823                         break;
1824         }
1825
1826         return cf_itemtopair(ci);
1827 }
1828
1829 /*
1830  * Find a CONF_SECTION, or return the root if name is NULL
1831  */
1832
1833 CONF_SECTION *cf_section_find(const char *name)
1834 {
1835         if (name)
1836                 return cf_section_sub_find(mainconfig.config, name);
1837         else
1838                 return mainconfig.config;
1839 }
1840
1841 /*
1842  * Find a sub-section in a section
1843  */
1844
1845 CONF_SECTION *cf_section_sub_find(const CONF_SECTION *cs, const char *name)
1846 {
1847         CONF_ITEM *ci;
1848
1849         /*
1850          *      Do the fast lookup if possible.
1851          */
1852         if (name && cs->section_tree) {
1853                 CONF_SECTION mycs;
1854
1855                 mycs.name1 = name;
1856                 mycs.name2 = NULL;
1857                 return rbtree_finddata(cs->section_tree, &mycs);
1858         }
1859
1860         for (ci = cs->children; ci; ci = ci->next) {
1861                 if (ci->type != CONF_ITEM_SECTION)
1862                         continue;
1863                 if (strcmp(cf_itemtosection(ci)->name1, name) == 0)
1864                         break;
1865         }
1866
1867         return cf_itemtosection(ci);
1868
1869 }
1870
1871
1872 /*
1873  *      Find a CONF_SECTION with both names.
1874  */
1875 CONF_SECTION *cf_section_sub_find_name2(const CONF_SECTION *cs,
1876                                         const char *name1, const char *name2)
1877 {
1878         CONF_ITEM    *ci;
1879
1880         if (!cs) cs = mainconfig.config;
1881
1882         if (name1 && (cs->section_tree)) {
1883                 CONF_SECTION mycs, *master_cs;
1884
1885                 mycs.name1 = name1;
1886                 mycs.name2 = name2;
1887
1888                 master_cs = rbtree_finddata(cs->section_tree, &mycs);
1889                 if (master_cs) {
1890                         return rbtree_finddata(master_cs->name2_tree, &mycs);
1891                 }
1892         }
1893
1894         /*
1895          *      Else do it the old-fashioned way.
1896          */
1897         for (ci = cs->children; ci; ci = ci->next) {
1898                 CONF_SECTION *subcs;
1899
1900                 if (ci->type != CONF_ITEM_SECTION)
1901                         continue;
1902
1903                 subcs = cf_itemtosection(ci);
1904                 if (!name1) {
1905                         if (!subcs->name2) {
1906                                 if (strcmp(subcs->name1, name2) == 0) break;
1907                         } else {
1908                                 if (strcmp(subcs->name2, name2) == 0) break;
1909                         }
1910                         continue; /* don't do the string comparisons below */
1911                 }
1912
1913                 if ((strcmp(subcs->name1, name1) == 0) &&
1914                     (subcs->name2 != NULL) &&
1915                     (strcmp(subcs->name2, name2) == 0))
1916                         break;
1917         }
1918
1919         return cf_itemtosection(ci);
1920 }
1921
1922 /*
1923  * Return the next subsection after a CONF_SECTION
1924  * with a certain name1 (char *name1). If the requested
1925  * name1 is NULL, any name1 matches.
1926  */
1927
1928 CONF_SECTION *cf_subsection_find_next(CONF_SECTION *section,
1929                                       CONF_SECTION *subsection,
1930                                       const char *name1)
1931 {
1932         CONF_ITEM       *ci;
1933
1934         /*
1935          * If subsection is NULL this must be a first time run
1936          * Find the subsection with correct name
1937          */
1938
1939         if (subsection == NULL){
1940                 ci = section->children;
1941         } else {
1942                 ci = cf_sectiontoitem(subsection)->next;
1943         }
1944
1945         for (; ci; ci = ci->next) {
1946                 if (ci->type != CONF_ITEM_SECTION)
1947                         continue;
1948                 if ((name1 == NULL) ||
1949                     (strcmp(cf_itemtosection(ci)->name1, name1) == 0))
1950                         break;
1951         }
1952
1953         return cf_itemtosection(ci);
1954 }
1955
1956
1957 /*
1958  * Return the next section after a CONF_SECTION
1959  * with a certain name1 (char *name1). If the requested
1960  * name1 is NULL, any name1 matches.
1961  */
1962
1963 CONF_SECTION *cf_section_find_next(CONF_SECTION *section,
1964                                    CONF_SECTION *subsection,
1965                                    const char *name1)
1966 {
1967         if (!section->item.parent) return NULL;
1968
1969         return cf_subsection_find_next(section->item.parent, subsection, name1);
1970 }
1971
1972 /*
1973  * Return the next item after a CONF_ITEM.
1974  */
1975
1976 CONF_ITEM *cf_item_find_next(CONF_SECTION *section, CONF_ITEM *item)
1977 {
1978         /*
1979          * If item is NULL this must be a first time run
1980          * Return the first item
1981          */
1982
1983         if (item == NULL) {
1984                 return section->children;
1985         } else {
1986                 return item->next;
1987         }
1988 }
1989
1990 int cf_section_lineno(CONF_SECTION *section)
1991 {
1992         return cf_sectiontoitem(section)->lineno;
1993 }
1994
1995 const char *cf_pair_filename(CONF_PAIR *pair)
1996 {
1997         return cf_pairtoitem(pair)->filename;
1998 }
1999
2000 const char *cf_section_filename(CONF_SECTION *section)
2001 {
2002         return cf_sectiontoitem(section)->filename;
2003 }
2004
2005 int cf_pair_lineno(CONF_PAIR *pair)
2006 {
2007         return cf_pairtoitem(pair)->lineno;
2008 }
2009
2010 int cf_item_is_section(CONF_ITEM *item)
2011 {
2012         return item->type == CONF_ITEM_SECTION;
2013 }
2014 int cf_item_is_pair(CONF_ITEM *item)
2015 {
2016         return item->type == CONF_ITEM_PAIR;
2017 }
2018
2019
2020 static CONF_DATA *cf_data_alloc(CONF_SECTION *parent, const char *name,
2021                                 void *data, void (*data_free)(void *))
2022 {
2023         char *p;
2024         size_t name_len;
2025         CONF_DATA *cd;
2026
2027         name_len = strlen(name) + 1;
2028
2029         p = rad_malloc(sizeof(*cd) + name_len);
2030         cd = (CONF_DATA *) p;
2031         memset(cd, 0, sizeof(*cd));
2032
2033         cd->item.type = CONF_ITEM_DATA;
2034         cd->item.parent = parent;
2035         cd->data = data;
2036         cd->free = data_free;
2037
2038         p += sizeof(*cd);
2039         memcpy(p, name, name_len);
2040         cd->name = p;
2041         return cd;
2042 }
2043
2044
2045 static void *cf_data_find_internal(CONF_SECTION *cs, const char *name,
2046                                    int flag)
2047 {
2048         if (!cs || !name) return NULL;
2049
2050         /*
2051          *      Find the name in the tree, for speed.
2052          */
2053         if (cs->data_tree) {
2054                 CONF_DATA mycd;
2055
2056                 mycd.name = name;
2057                 mycd.flag = flag;
2058                 return rbtree_finddata(cs->data_tree, &mycd);
2059         }
2060
2061         return NULL;
2062 }
2063
2064 /*
2065  *      Find data from a particular section.
2066  */
2067 void *cf_data_find(CONF_SECTION *cs, const char *name)
2068 {
2069         CONF_DATA *cd = cf_data_find_internal(cs, name, 0);
2070
2071         if (cd) return cd->data;
2072         return NULL;
2073 }
2074
2075
2076 /*
2077  *      Add named data to a configuration section.
2078  */
2079 static int cf_data_add_internal(CONF_SECTION *cs, const char *name,
2080                                 void *data, void (*data_free)(void *),
2081                                 int flag)
2082 {
2083         CONF_DATA *cd;
2084
2085         if (!cs || !name) return -1;
2086
2087         /*
2088          *      Already exists.  Can't add it.
2089          */
2090         if (cf_data_find_internal(cs, name, flag) != NULL) return -1;
2091
2092         cd = cf_data_alloc(cs, name, data, data_free);
2093         if (!cd) return -1;
2094         cd->flag = flag;
2095
2096         cf_item_add(cs, cf_datatoitem(cd));
2097
2098         return 0;
2099 }
2100
2101 /*
2102  *      Add named data to a configuration section.
2103  */
2104 int cf_data_add(CONF_SECTION *cs, const char *name,
2105                 void *data, void (*data_free)(void *))
2106 {
2107         return cf_data_add_internal(cs, name, data, data_free, 0);
2108 }
2109
2110
2111 /*
2112  *      Copy CONF_DATA from src to dst
2113  */
2114 static void cf_section_copy_data(CONF_SECTION *s, CONF_SECTION *d)
2115 {
2116
2117         CONF_ITEM *cd, *next, **last;
2118
2119         /*
2120          *      Don't check if s->data_tree is NULL.  It's child
2121          *      sections may have data, even if this section doesn't.
2122          */
2123
2124         rad_assert(d->data_tree == NULL);
2125         d->data_tree = s->data_tree;
2126         s->data_tree = NULL;
2127
2128         /*
2129          *      Walk through src, moving CONF_ITEM_DATA
2130          *      to dst, by hand.
2131          */
2132         last = &(s->children);
2133         for (cd = s->children; cd != NULL; cd = next) {
2134                 next = cd->next;
2135
2136                 /*
2137                  *      Recursively copy data from child sections.
2138                  */
2139                 if (cd->type == CONF_ITEM_SECTION) {
2140                         CONF_SECTION *s1, *d1;
2141
2142                         s1 = cf_itemtosection(cd);
2143                         d1 = cf_section_sub_find_name2(d, s1->name1, s1->name2);
2144                         if (d1) {
2145                                 cf_section_copy_data(s1, d1);
2146                         }
2147                         last = &(cd->next);
2148                         continue;
2149                 }
2150
2151                 /*
2152                  *      Not conf data, remember last ptr.
2153                  */
2154                 if (cd->type != CONF_ITEM_DATA) {
2155                         last = &(cd->next);
2156                         continue;
2157                 }
2158
2159                 /*
2160                  *      Remove it from the src list
2161                  */
2162                 *last = cd->next;
2163                 cd->next = NULL;
2164
2165                 /*
2166                  *      Add it to the dst list
2167                  */
2168                 if (!d->children) {
2169                         rad_assert(d->tail == NULL);
2170                         d->children = cd;
2171                 } else {
2172                         rad_assert(d->tail != NULL);
2173                         d->tail->next = cd;
2174                 }
2175                 d->tail = cd;
2176         }
2177 }
2178
2179 /*
2180  *      For a CONF_DATA element, stat the filename, if necessary.
2181  */
2182 static int filename_stat(void *context, void *data)
2183 {
2184         struct stat buf;
2185         CONF_DATA *cd = data;
2186
2187         context = context;      /* -Wunused */
2188
2189         if (cd->flag != PW_TYPE_FILENAME) return 0;
2190
2191         if (stat(cd->name, &buf) < 0) return -1;
2192
2193         if (buf.st_mtime != *(time_t *) cd->data) return -1;
2194
2195         return 0;
2196 }
2197
2198
2199 /*
2200  *      Compare two CONF_SECTIONS.  The items MUST be in the same
2201  *      order.
2202  */
2203 static int cf_section_cmp(CONF_SECTION *a, CONF_SECTION *b)
2204 {
2205         CONF_ITEM *ca = a->children;
2206         CONF_ITEM *cb = b->children;
2207
2208         while (1) {
2209                 CONF_PAIR *pa, *pb;
2210
2211                 /*
2212                  *      Done.  Stop.
2213                  */
2214                 if (!ca && !cb) break;
2215
2216                 /*
2217                  *      Skip CONF_DATA.
2218                  */
2219                 if (ca && ca->type == CONF_ITEM_DATA) {
2220                         ca = ca->next;
2221                         continue;
2222                 }
2223                 if (cb && cb->type == CONF_ITEM_DATA) {
2224                         cb = cb->next;
2225                         continue;
2226                 }
2227
2228                 /*
2229                  *      One is smaller than the other.  Exit.
2230                  */
2231                 if (!ca || !cb) return 0;
2232
2233                 if (ca->type != cb->type) return 0;
2234
2235                 /*
2236                  *      Deal with subsections.
2237                  */
2238                 if (ca->type == CONF_ITEM_SECTION) {
2239                         CONF_SECTION *sa = cf_itemtosection(ca);
2240                         CONF_SECTION *sb = cf_itemtosection(cb);
2241
2242                         if (!cf_section_cmp(sa, sb)) return 0;
2243                         goto next;
2244                 }
2245
2246                 rad_assert(ca->type == CONF_ITEM_PAIR);
2247
2248                 pa = cf_itemtopair(ca);
2249                 pb = cf_itemtopair(cb);
2250
2251                 /*
2252                  *      Different attr and/or value, Exit.
2253                  */
2254                 if ((strcmp(pa->attr, pb->attr) != 0) ||
2255                     (strcmp(pa->value, pb->value) != 0)) return 0;
2256
2257
2258                 /*
2259                  *      And go to the next element.
2260                  */
2261         next:
2262                 ca = ca->next;
2263                 cb = cb->next;
2264         }
2265
2266         /*
2267          *      Walk over the CONF_DATA, stat'ing PW_TYPE_FILENAME.
2268          */
2269         if (a->data_tree &&
2270             (rbtree_walk(a->data_tree, InOrder, filename_stat, NULL) != 0)) {
2271                 return 0;
2272         }
2273
2274         /*
2275          *      They must be the same, say so.
2276          */
2277         return 1;
2278 }
2279
2280
2281 /*
2282  *      Migrate CONF_DATA from one section to another.
2283  */
2284 int cf_section_migrate(CONF_SECTION *dst, CONF_SECTION *src)
2285 {
2286         CONF_ITEM *ci;
2287         CONF_SECTION *s, *d;
2288
2289         for (ci = src->children; ci != NULL; ci = ci->next) {
2290                 if (ci->type != CONF_ITEM_SECTION)
2291                         continue;
2292
2293                 s = cf_itemtosection(ci);
2294                 d = cf_section_sub_find_name2(dst, s->name1, s->name2);
2295
2296                 if (!d) continue; /* not in new one, don't migrate it */
2297
2298                 /*
2299                  *      A section of the same name is in BOTH src & dst,
2300                  *      compare the CONF_PAIR's.  If they're all the same,
2301                  *      then copy the CONF_DATA from one to the other.
2302                  */
2303                 if (cf_section_cmp(s, d)) {
2304                         cf_section_copy_data(s, d);
2305                 }
2306         }
2307
2308         return 1;               /* rcode means anything? */
2309 }
2310
2311 int cf_section_template(CONF_SECTION *cs, CONF_SECTION *template)
2312 {
2313         if (!cs || !template || cs->template || template->template) return -1;
2314
2315         cs->template = template;
2316
2317         return 0;
2318 }
2319
2320
2321 /*
2322  *      This is here to make the rest of the code easier to read.  It
2323  *      ties conffile.c to log.c, but it means we don't have to
2324  *      pollute the 
2325  */
2326 void cf_log_err(CONF_ITEM *ci, const char *fmt, ...)
2327 {
2328         va_list ap;
2329         char buffer[256];
2330
2331         va_start(ap, fmt);
2332         vsnprintf(buffer, sizeof(buffer), fmt, ap);
2333         va_end(ap);
2334
2335         radlog(L_ERR, "%s[%d]: %s", ci->filename, ci->lineno, buffer);
2336 }
2337
2338
2339 #if 0
2340 /*
2341  * JMG dump_config tries to dump the config structure in a readable format
2342  *
2343 */
2344
2345 static int dump_config_section(CONF_SECTION *cs, int indent)
2346 {
2347         CONF_SECTION    *scs;
2348         CONF_PAIR       *cp;
2349         CONF_ITEM       *ci;
2350
2351         /* The DEBUG macro doesn't let me
2352          *   for(i=0;i<indent;++i) debugputchar('\t');
2353          * so I had to get creative. --Pac. */
2354
2355         for (ci = cs->children; ci; ci = ci->next) {
2356                 switch (ci->type) {
2357                 case CONF_ITEM_PAIR:
2358                         cp=cf_itemtopair(ci);
2359                         DEBUG("%.*s%s = %s",
2360                                 indent, "\t\t\t\t\t\t\t\t\t\t\t",
2361                                 cp->attr, cp->value);
2362                         break;
2363
2364                 case CONF_ITEM_SECTION:
2365                         scs=cf_itemtosection(ci);
2366                         DEBUG("%.*s%s %s%s{",
2367                                 indent, "\t\t\t\t\t\t\t\t\t\t\t",
2368                                 scs->name1,
2369                                 scs->name2 ? scs->name2 : "",
2370                                 scs->name2 ?  " " : "");
2371                         dump_config_section(scs, indent+1);
2372                         DEBUG("%.*s}",
2373                                 indent, "\t\t\t\t\t\t\t\t\t\t\t");
2374                         break;
2375
2376                 default:        /* FIXME: Do more! */
2377                         break;
2378                 }
2379         }
2380
2381         return 0;
2382 }
2383
2384 int dump_config(CONF_SECTION *cs)
2385 {
2386         return dump_config_section(cs, 0);
2387 }
2388 #endif