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