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