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