22e81a152cc07ba49e53275c95874eed32499989
[freeradius.git] / src / lib / dict.c
1 /*
2  * dict.c       Routines to read the dictionary file.
3  *
4  * Version:     $Id$
5  *
6  *   This library is free software; you can redistribute it and/or
7  *   modify it under the terms of the GNU Lesser General Public
8  *   License as published by the Free Software Foundation; either
9  *   version 2.1 of the License, or (at your option) any later version.
10  *
11  *   This library is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  *   Lesser General Public License for more details.
15  *
16  *   You should have received a copy of the GNU Lesser General Public
17  *   License along with this library; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2000  The FreeRADIUS server project
21  */
22
23 static const char rcsid[] = "$Id$";
24
25 #include        "autoconf.h"
26
27 #include        <stdlib.h>
28 #include        <ctype.h>
29 #include        <string.h>
30
31 #ifdef HAVE_MALLOC_H
32 #include        <malloc.h>
33 #endif
34
35 #ifdef HAVE_SYS_STAT_H
36 #include        <sys/stat.h>
37 #endif
38
39 #include        <unistd.h>
40
41 #include        "missing.h"
42 #include        "libradius.h"
43
44 #define DICT_VALUE_MAX_NAME_LEN (128)
45 #define DICT_VENDOR_MAX_NAME_LEN (128)
46
47 static lrad_hash_table_t *vendors_byname = NULL;
48 static lrad_hash_table_t *vendors_byvalue = NULL;
49
50 static lrad_hash_table_t *attributes_byname = NULL;
51 static lrad_hash_table_t *attributes_byvalue = NULL;
52
53 static lrad_hash_table_t *values_byvalue = NULL;
54 static lrad_hash_table_t *values_byname = NULL;
55
56 /*
57  *      For faster HUP's, we cache the stat information for
58  *      files we've $INCLUDEd
59  */
60 typedef struct dict_stat_t {
61         struct dict_stat_t *next;
62         char               *name;
63         time_t             mtime;
64 } dict_stat_t;
65
66 static char *stat_root_dir = NULL;
67 static char *stat_root_file = NULL;
68
69 static dict_stat_t *stat_head = NULL;
70 static dict_stat_t *stat_tail = NULL;
71
72 typedef struct value_fixup_t {
73         char            attrstr[40];
74         uint32_t        hash;
75         DICT_VALUE      *dval;
76         struct value_fixup_t *next;
77 } value_fixup_t;
78
79
80 /*
81  *      So VALUEs in the dictionary can have forward references.
82  */
83 static value_fixup_t *value_fixup = NULL;
84
85 static const LRAD_NAME_NUMBER type_table[] = {
86         { "string",     PW_TYPE_STRING },
87         { "integer",    PW_TYPE_INTEGER },
88         { "ipaddr",     PW_TYPE_IPADDR },
89         { "date",       PW_TYPE_DATE },
90         { "abinary",    PW_TYPE_ABINARY },
91         { "octets",     PW_TYPE_OCTETS },
92         { "ifid",       PW_TYPE_IFID },
93         { "ipv6addr",   PW_TYPE_IPV6ADDR },
94         { "ipv6prefix", PW_TYPE_IPV6PREFIX },
95         { NULL, 0 }
96 };
97
98 /*
99  *      Create the hash of the name.
100  */
101 static uint32_t dict_hashname(const char *name)
102 {
103         const char *p;
104         char *q;
105         size_t len = 0;
106         char buffer[1024];
107         
108         p = name;
109         q = buffer;
110         while (*p && (len < sizeof(buffer))) {
111                 if (isalpha(*p)) {
112                         *(q++) = tolower((int) *(p++));
113                 } else {
114                         *(q++) = *(p++);
115                 }
116                 len++;
117         }
118         return lrad_hash(buffer, len);
119 }
120
121
122 /*
123  *      Free the list of stat buffers
124  */
125 static void dict_stat_free(void)
126 {
127         dict_stat_t *this, *next;
128
129         free(stat_root_dir);
130         stat_root_dir = NULL;
131         free(stat_root_file);
132         stat_root_file = NULL;
133
134         if (!stat_head) {
135                 stat_tail = NULL;
136                 return;
137         }
138
139         for (this = stat_head; this != NULL; this = next) {
140                 next = this->next;
141                 free(this->name);
142                 free(this);
143         }
144
145         stat_head = stat_tail = NULL;
146 }
147
148
149 /*
150  *      Add an entry to the list of stat buffers.
151  */
152 static void dict_stat_add(const char *name, const struct stat *stat_buf)
153 {
154         dict_stat_t *this;
155
156         this = malloc(sizeof(*this));
157         memset(this, 0, sizeof(*this));
158
159         this->name = strdup(name);
160         this->mtime = stat_buf->st_mtime;
161
162         if (!stat_head) {
163                 stat_head = stat_tail = this;
164         } else {
165                 stat_tail->next = this;
166                 stat_tail = this;
167         }
168 }
169
170
171 /*
172  *      See if any dictionaries have changed.  If not, don't
173  *      do anything.
174  */
175 static int dict_stat_check(const char *root_dir, const char *root_file)
176 {
177         struct stat buf;
178         dict_stat_t *this;
179
180         if (!stat_root_dir) return 0;
181         if (!stat_root_file) return 0;
182
183         if (strcmp(root_dir, stat_root_dir) != 0) return 0;
184         if (strcmp(root_file, stat_root_file) != 0) return 0;
185
186         if (!stat_head) return 0; /* changed, reload */
187
188         for (this = stat_head; this != NULL; this = this->next) {
189                 if (stat(this->name, &buf) < 0) return 0;
190
191                 if (buf.st_mtime != this->mtime) return 0;
192         }
193
194         return 1;
195 }
196
197
198 /*
199  *      Free the dictionary_attributes and dictionary_values lists.
200  */
201 void dict_free(void)
202 {
203         /*
204          *      Free the trees
205          */
206         lrad_hash_table_free(vendors_byname);
207         lrad_hash_table_free(vendors_byvalue);
208         vendors_byname = NULL;
209         vendors_byvalue = NULL;
210
211         lrad_hash_table_free(attributes_byname);
212         lrad_hash_table_free(attributes_byvalue);
213         attributes_byname = NULL;
214         attributes_byvalue = NULL;
215
216         lrad_hash_table_free(values_byname);
217         lrad_hash_table_free(values_byvalue);
218         values_byname = NULL;
219         values_byvalue = NULL;
220
221         dict_stat_free();
222 }
223
224
225 /*
226  *      Add vendor to the list.
227  */
228 int dict_addvendor(const char *name, int value)
229 {
230         size_t length;
231         uint32_t hash;
232         DICT_VENDOR *dv;
233
234         if (value >= (1 << 16)) {
235                 librad_log("dict_addvendor: Cannot handle vendor ID larger than 65535");
236                 return -1;
237         }
238
239         if ((length = strlen(name)) >= DICT_VENDOR_MAX_NAME_LEN) {
240                 librad_log("dict_addvendor: vendor name too long");
241                 return -1;
242         }
243         
244         if ((dv = malloc(sizeof(*dv) + length)) == NULL) {
245                 librad_log("dict_addvendor: out of memory");
246                 return -1;
247         }
248
249         hash = dict_hashname(name);
250         strcpy(dv->name, name);
251         dv->vendorpec  = value;
252         dv->type = dv->length = 1; /* defaults */
253
254         if (!lrad_hash_table_insert(vendors_byname, hash, dv)) {
255                 DICT_VENDOR *old_dv;
256
257                 old_dv = lrad_hash_table_finddata(vendors_byname, hash);
258                 if (!old_dv) {
259                         librad_log("dict_addvendor: Failed inserting vendor name %s", name);
260                         return -1;
261                 }
262                 if (old_dv->vendorpec != dv->vendorpec) {
263                         librad_log("dict_addvendor: Duplicate vendor name %s", name);
264                         return -1;
265                 }
266
267                 /*
268                  *      Already inserted.  Discard the duplicate entry.
269                  */
270                 free(dv);
271                 return 0;
272         }
273
274         /*
275          *      Insert the SAME pointer (not free'd when this tree is
276          *      deleted), into another tree.
277          *
278          *      If the newly inserted entry is a duplicate of an existing
279          *      entry, then the old entry is tossed, and the new one
280          *      replaces it.  This behaviour is configured in the
281          *      lrad_hash_table_create() function.
282          *
283          *      We want this behaviour because we want OLD names for
284          *      the attributes to be read from the configuration
285          *      files, but when we're printing them, (and looking up
286          *      by value) we want to use the NEW name.
287          */
288         if (!lrad_hash_table_insert(vendors_byvalue,
289                                     lrad_hash(&dv->vendorpec,
290                                               sizeof(dv->vendorpec)),
291                                     dv)) {
292                 librad_log("dict_addvendor: Failed inserting vendor %s",
293                            name);
294                 return -1;
295         }
296
297         return 0;
298 }
299
300 /*
301  *      Add an attribute to the dictionary.
302  */
303 int dict_addattr(const char *name, int vendor, int type, int value,
304                  ATTR_FLAGS flags)
305 {
306         static int      max_attr = 0;
307         uint32_t        hash;
308         DICT_ATTR       *attr;
309
310         if (strlen(name) > (sizeof(attr->name) -1)) {
311                 librad_log("dict_addattr: attribute name too long");
312                 return -1;
313         }
314
315         /*
316          *      If the value is '-1', that means use a pre-existing
317          *      one (if it already exists).  If one does NOT already exist,
318          *      then create a new attribute, with a non-conflicting value,
319          *      and use that.
320          */
321         if (value == -1) {
322                 if (dict_attrbyname(name)) {
323                         return 0; /* exists, don't add it again */
324                 }
325
326                 value = ++max_attr;
327
328         } else if (vendor == 0) {
329                 /*
330                  *  Update 'max_attr'
331                  */
332                 if (value > max_attr) {
333                         max_attr = value;
334                 }
335         }
336
337         if (value < 0) {
338                 librad_log("dict_addattr: ATTRIBUTE has invalid number (less than zero)");
339                 return -1;
340         }
341
342         if (value >= 65536) {
343                 librad_log("dict_addattr: ATTRIBUTE has invalid number (larger than 65535).");
344                 return -1;
345         }
346
347         if (vendor) {
348                 DICT_VENDOR *dv = dict_vendorbyvalue(vendor);
349
350                 /*
351                  *      If the vendor isn't defined, die/
352                  */
353                 if (!dv) {
354                         librad_log("dict_addattr: Unknown vendor");
355                         return -1;
356                 }
357
358                 /*
359                  *      With a few exceptions, attributes can only be
360                  *      1..255.  The check above catches the less than
361                  *      zero case.
362                  */
363                 if ((dv->type == 1) && (value >= 256)) {
364                         librad_log("dict_addattr: ATTRIBUTE has invalid number (larger than 255).");
365                         return -1;
366                 } /* else 256..65535 are allowed */
367         }
368
369         /*
370          *      Create a new attribute for the list
371          */
372         if ((attr = malloc(sizeof(*attr))) == NULL) {
373                 librad_log("dict_addattr: out of memory");
374                 return -1;
375         }
376
377         hash = dict_hashname(name);
378         strcpy(attr->name, name);
379         attr->attr = value;
380         attr->attr |= (vendor << 16); /* FIXME: hack */
381         attr->type = type;
382         attr->flags = flags;
383         attr->vendor = vendor;
384
385
386         /*
387          *      Insert the attribute, only if it's not a duplicate.
388          */
389         if (!lrad_hash_table_insert(attributes_byname, hash, attr)) {
390                 DICT_ATTR       *a;
391
392                 /*
393                  *      If the attribute has identical number, then
394                  *      ignore the duplicate.
395                  */
396                 a = lrad_hash_table_finddata(attributes_byname, hash);
397                 if (a && (strcasecmp(a->name, attr->name) == 0)) {
398                         if (a->attr != attr->attr) {
399                                 librad_log("dict_addattr: Duplicate attribute name %s", name);
400                                 return -1;
401                         }
402
403                         /*
404                          *      Same name, same vendor, same attr,
405                          *      maybe the flags and/or type is
406                          *      different.  Let the new value
407                          *      over-ride the old one.
408                          */
409                 }
410         }
411
412         /*
413          *      Insert the SAME pointer (not free'd when this tree is
414          *      deleted), into another tree.
415          *
416          *      If the newly inserted entry is a duplicate of an existing
417          *      entry, then the old entry is tossed, and the new one
418          *      replaces it.  This behaviour is configured in the
419          *      lrad_hash_table_create() function.
420          *
421          *      We want this behaviour because we want OLD names for
422          *      the attributes to be read from the configuration
423          *      files, but when we're printing them, (and looking up
424          *      by value) we want to use the NEW name.
425          */
426         if (!lrad_hash_table_insert(attributes_byvalue,
427                                     lrad_hash(&attr->attr, sizeof(attr->attr)),
428                                     attr)) {
429                 librad_log("dict_addattr: Failed inserting attribute attribute name %s", name);
430                 return -1;
431         }
432
433         return 0;
434 }
435
436
437 /*
438  *      Add a value for an attribute to the dictionary.
439  */
440 int dict_addvalue(const char *namestr, const char *attrstr, int value)
441 {
442         size_t          length;
443         DICT_ATTR       *dattr;
444         uint32_t        hash;
445         DICT_VALUE      *dval;
446
447         if ((length = strlen(namestr)) >= DICT_VALUE_MAX_NAME_LEN) {
448                 librad_log("dict_addvalue: value name too long");
449                 return -1;
450         }
451
452         if ((dval = malloc(sizeof(*dval) + length)) == NULL) {
453                 librad_log("dict_addvalue: out of memory");
454                 return -1;
455         }
456         memset(dval, 0, sizeof(*dval));
457
458         hash = dict_hashname(namestr);
459         strcpy(dval->name, namestr);
460         dval->value = value;
461
462         /*
463          *      Remember which attribute is associated with this
464          *      value, if possible.
465          */
466         dattr = dict_attrbyname(attrstr);
467         if (dattr) {
468                 dval->attr = dattr->attr;
469                 hash = lrad_hash_update(&dval->attr, sizeof(dval->attr), hash);
470         } else {
471                 value_fixup_t *fixup;
472                 
473                 fixup = (value_fixup_t *) malloc(sizeof(*fixup));
474                 if (!fixup) {
475                         librad_log("dict_addvalue: out of memory");
476                         return -1;
477                 }
478                 memset(fixup, 0, sizeof(*fixup));
479
480                 strNcpy(fixup->attrstr, attrstr, sizeof(fixup->attrstr));
481                 fixup->hash = hash;
482                 fixup->dval = dval;
483                 
484                 /*
485                  *      Insert to the head of the list.
486                  */
487                 fixup->next = value_fixup;
488                 value_fixup = fixup;
489
490                 return 0;
491         }
492
493         /*
494          *      Add the value into the dictionary.
495          */
496         if (!lrad_hash_table_insert(values_byname, hash, dval)) {
497                 if (dattr) {
498                         DICT_VALUE *old;
499                         
500                         /*
501                          *      Suppress duplicates with the same
502                          *      name and value.  There are lots in
503                          *      dictionary.ascend.
504                          */
505                         old = dict_valbyname(dattr->attr, namestr);
506                         if (old && (old->value == dval->value)) {
507                                 free(dval);
508                                 return 0;
509                         }
510                 }
511
512                 librad_log("dict_addvalue: Duplicate value name %s for attribute %s", namestr, attrstr);
513                 return -1;
514         }
515
516         /*
517          *      There are multiple VALUE's, keyed by attribute, so we
518          *      take care of that here.
519          */
520         hash = dval->attr;
521         hash = lrad_hash_update(&dval->value, sizeof(dval->value), hash);
522         if (!lrad_hash_table_insert(values_byvalue, hash, dval)) {      
523                 librad_log("dict_addvalue: Failed inserting value %s",
524                            namestr);
525                 return -1;
526         }
527
528         return 0;
529 }
530
531 /*
532  *      Process the ATTRIBUTE command
533  */
534 static int process_attribute(const char* fn, const int line,
535                              const int block_vendor, char **argv,
536                              int argc)
537 {
538         int             vendor = 0;
539         int             value;
540         int             type;
541         char            *s, *c;
542         ATTR_FLAGS      flags;
543
544         if ((argc < 3) || (argc > 4)) {
545                 librad_log("dict_init: %s[%d]: invalid ATTRIBUTE line",
546                         fn, line);
547                 return -1;
548         }
549
550         /*
551          *      Validate all entries
552          */
553         if (!isdigit((int) argv[1][0])) {
554                 librad_log("dict_init: %s[%d]: invalid value", fn, line);
555                 return -1;
556         }
557         sscanf(argv[1], "%i", &value);
558
559         /*
560          *      find the type of the attribute.
561          */
562         type = lrad_str2int(type_table, argv[2], -1);
563         if (type < 0) {
564                 librad_log("dict_init: %s[%d]: invalid type \"%s\"",
565                         fn, line, argv[2]);
566                 return -1;
567         }
568
569         /*
570          *      Only look up the vendor if the string
571          *      is non-empty.
572          */
573         memset(&flags, 0, sizeof(flags));
574         if (argc == 4) {
575                 s = strtok(argv[3], ",");
576                 while (s) {
577                         if (strcmp(s, "has_tag") == 0 ||
578                             strcmp(s, "has_tag=1") == 0) {
579                                 /* Boolean flag, means this is a
580                                    tagged attribute */
581                                 flags.has_tag = 1;
582                                 
583                         } else if (strncmp(s, "encrypt=", 8) == 0) {
584                                 /* Encryption method, defaults to 0 (none).
585                                    Currently valid is just type 2,
586                                    Tunnel-Password style, which can only
587                                    be applied to strings. */
588                                 flags.encrypt = strtol(s + 8, &c, 0);
589                                 if (*c) {
590                                         librad_log( "dict_init: %s[%d] invalid option %s",
591                                                     fn, line, s);
592                                         return -1;
593                                 }
594                         } else {
595                                 /* Must be a vendor 'flag'... */
596                                 if (strncmp(s, "vendor=", 7) == 0) {
597                                         /* New format */
598                                         s += 7;
599                                 }
600                                 
601                                 vendor = dict_vendorbyname(s);
602                                 if (!vendor) {
603                                         librad_log( "dict_init: %s[%d]: unknown vendor %s",
604                                                     fn, line, s);
605                                         return -1;
606                                 }
607                                 if (block_vendor && argv[3][0] &&
608                                     (block_vendor != vendor)) {
609                                         librad_log("dict_init: %s[%d]: mismatched vendor %s within BEGIN-VENDOR/END-VENDOR block",
610                                                    fn, line, argv[3]);
611                                         return -1;
612                                 }
613                         }
614                         s = strtok(NULL, ",");
615                 }
616         }
617
618         if (block_vendor) vendor = block_vendor;
619
620         /*
621          *      Special checks for tags, they make our life much more
622          *      difficult.
623          */
624         if (flags.has_tag) {
625                 /*
626                  *      VSA's can't be tagged.
627                  */
628                 if (vendor) {
629                         librad_log("dict_init: %s[%d]: Vendor attributes cannot be tagged.",
630                                    fn, line);
631                         return -1;
632                 }
633
634                 /*
635                  *      Only string, octets, and integer can be tagged.
636                  */
637                 switch (type) {
638                 case PW_TYPE_STRING:
639                 case PW_TYPE_INTEGER:
640                         break;
641
642                 default:
643                         librad_log("dict_init: %s[%d]: Attributes of type %s cannot be tagged.",
644                                    fn, line,
645                                    lrad_int2str(type_table, type, "?Unknown?"));
646                         return -1;
647                         
648                 }
649         }
650
651         /*
652          *      Add it in.
653          */
654         if (dict_addattr(argv[0], vendor, type, value, flags) < 0) {
655                 librad_log("dict_init: %s[%d]: %s",
656                            fn, line, librad_errstr);
657                 return -1;
658         }
659
660         return 0;
661 }
662
663
664 /*
665  *      Process the VALUE command
666  */
667 static int process_value(const char* fn, const int line, char **argv,
668                          int argc)
669 {
670         int     value;
671
672         if (argc != 3) {
673                 librad_log("dict_init: %s[%d]: invalid VALUE line",
674                         fn, line);
675                 return -1;
676         }
677         /*
678          *      For Compatibility, skip "Server-Config"
679          */
680         if (strcasecmp(argv[0], "Server-Config") == 0)
681                 return 0;
682
683         /*
684          *      Validate all entries
685          */
686         if (!isdigit((int) argv[2][0])) {
687                 librad_log("dict_init: %s[%d]: invalid value",
688                         fn, line);
689                 return -1;
690         }
691         sscanf(argv[2], "%i", &value);
692
693         /*
694          *      valuepair.c will get excited when creating attributes,
695          *      if it sees values which look like integers, so we can't
696          *      use them here.
697          */
698         if (isdigit(argv[1][0])) {
699                 librad_log("dict_init: %s[%d]: Names for VALUEs cannot start with a digit.",
700                            fn, line);
701         }
702         
703         if (dict_addvalue(argv[1], argv[0], value) < 0) {
704                 librad_log("dict_init: %s[%d]: %s",
705                            fn, line, librad_errstr);
706                 return -1;
707         }
708
709         return 0;
710 }
711
712
713 /*
714  *      Process the VENDOR command
715  */
716 static int process_vendor(const char* fn, const int line, char **argv,
717                           int argc)
718 {
719         int     value;
720         const   char *format = NULL;
721
722         if ((argc < 2) || (argc > 3)) {
723                 librad_log( "dict_init: %s[%d] invalid VENDOR entry",
724                             fn, line);
725                 return -1;
726         }
727
728         /*
729          *       Validate all entries
730          */
731         if (!isdigit((int) argv[1][0])) {
732                 librad_log("dict_init: %s[%d]: invalid value",
733                         fn, line);
734                 return -1;
735         }
736         value = atoi(argv[1]);
737
738         /* Create a new VENDOR entry for the list */
739         if (dict_addvendor(argv[0], value) < 0) {
740                 librad_log("dict_init: %s[%d]: %s",
741                            fn, line, librad_errstr);
742                 return -1;
743         }
744
745         /*
746          *      Look for a format statement
747          */
748         if (argc == 3) {
749                 format = argv[2];
750
751         } else if (value == VENDORPEC_USR) { /* catch dictionary screw-ups */
752                 format = "format=4,0";
753
754         } else if (value == VENDORPEC_LUCENT) {
755                 format = "format=2,1";
756
757         } else if (value == VENDORPEC_STARENT) {
758                 format = "format=2,2";
759
760         } /* else no fixups to do */
761
762         if (format) {
763                 int type, length;
764                 const char *p;
765                 DICT_VENDOR *dv;
766
767                 if (strncasecmp(format, "format=", 7) != 0) {
768                         librad_log("dict_init: %s[%d]: Invalid format for VENDOR.  Expected \"format=\", got \"%s\"",
769                                    fn, line, format);
770                         return -1;
771                 }
772
773                 p = format + 7;
774                 if ((strlen(p) != 3) || 
775                     !isdigit((int) p[0]) ||
776                     (p[1] != ',') ||
777                     !isdigit((int) p[2])) {
778                         librad_log("dict_init: %s[%d]: Invalid format for VENDOR.  Expected text like \"1,1\", got \"%s\"",
779                                    fn, line, p);
780                         return -1;
781                 }
782
783                 type = (int) (p[0] - '0');
784                 length = (int) (p[2] - '0');
785
786                 dv = dict_vendorbyvalue(value);
787                 if (!dv) {
788                         librad_log("dict_init: %s[%d]: Failed adding format for VENDOR",
789                                    fn, line);
790                         return -1;
791                 }
792
793                 if ((type != 1) && (type != 2) && (type != 4)) {
794                         librad_log("dict_init: %s[%d]: invalid type value %d for VENDOR",
795                                    fn, line, type);
796                         return -1;
797                 }
798
799                 if ((length != 0) && (length != 1) && (length != 2)) {
800                         librad_log("dict_init: %s[%d]: invalid length value %d for VENDOR",
801                                    fn, line, length);
802                         return -1;
803                 }
804
805                 dv->type = type;
806                 dv->length = length;
807         }
808
809         return 0;
810 }
811
812 /*
813  *      String split routine.  Splits an input string IN PLACE
814  *      into pieces, based on spaces.
815  */
816 static int str2argv(char *str, char **argv, int max_argc)
817 {
818         int argc = 0;
819
820         while (*str) {
821                 if (argc >= max_argc) return argc;
822
823                 /*
824                  *      Chop out comments early.
825                  */
826                 if (*str == '#') {
827                         *str = '\0';
828                         break;
829                 }
830
831                 while ((*str == ' ') ||
832                        (*str == '\t') ||
833                        (*str == '\r') ||
834                        (*str == '\n')) *(str++) = '\0';
835
836                 if (!*str) return argc;
837
838                 argv[argc] = str;
839                 argc++;
840
841                 while (*str &&
842                        (*str != ' ') &&
843                        (*str != '\t') &&
844                        (*str != '\r') &&
845                        (*str != '\n')) str++;
846         }
847
848         return argc;
849 }
850
851 #define MAX_ARGV (16)
852
853 /*
854  *      Initialize the dictionary.
855  */
856 static int my_dict_init(const char *dir, const char *fn,
857                         const char *src_file, int src_line)
858 {
859         FILE    *fp;
860         char    dirtmp[256];
861         char    buf[256];
862         char    *p;
863         int     line = 0;
864         int     vendor;
865         int     block_vendor;
866         struct stat statbuf;
867         char    *argv[MAX_ARGV];
868         int     argc;
869
870         if (strlen(fn) >= sizeof(dirtmp) / 2 ||
871             strlen(dir) >= sizeof(dirtmp) / 2) {
872                 librad_log("dict_init: filename name too long");
873                 return -1;
874         }
875
876         /*
877          *      First see if fn is relative to dir. If so, create
878          *      new filename. If not, remember the absolute dir.
879          */
880         if ((p = strrchr(fn, '/')) != NULL) {
881                 strcpy(dirtmp, fn);
882                 dirtmp[p - fn] = 0;
883                 dir = dirtmp;
884         } else if (dir && dir[0] && strcmp(dir, ".") != 0) {
885                 snprintf(dirtmp, sizeof(dirtmp), "%s/%s", dir, fn);
886                 fn = dirtmp;
887         }
888
889         if ((fp = fopen(fn, "r")) == NULL) {
890                 if (!src_file) {
891                         librad_log("dict_init: Couldn't open dictionary \"%s\": %s",
892                                    fn, strerror(errno));
893                 } else {
894                         librad_log("dict_init: %s[%d]: Couldn't open dictionary \"%s\": %s",
895                                    src_file, src_line, fn, strerror(errno));
896                 }
897                 return -1;
898         }
899
900         stat(fn, &statbuf); /* fopen() guarantees this will succeed */
901         if (!S_ISREG(statbuf.st_mode)) {
902                 fclose(fp);
903                 librad_log("dict_init: Dictionary \"%s\" is not a regular file",
904                            fn);
905                 return -1;        
906         }
907         dict_stat_add(fn, &statbuf);
908
909         /*
910          *      Seed the random pool with data.
911          */
912         lrad_rand_seed(&statbuf, sizeof(statbuf));
913
914         block_vendor = 0;
915
916         while (fgets(buf, sizeof(buf), fp) != NULL) {
917                 line++;
918                 if (buf[0] == '#' || buf[0] == 0 ||
919                     buf[0] == '\n' || buf[0] == '\r')
920                         continue;
921
922                 /*
923                  *  Comment characters should NOT be appearing anywhere but
924                  *  as start of a comment;
925                  */
926                 p = strchr(buf, '#');
927                 if (p) *p = '\0';
928
929                 argc = str2argv(buf, argv, MAX_ARGV);
930                 if (argc == 0) continue;
931
932                 if (argc == 1) {
933                         librad_log( "dict_init: %s[%d] invalid entry",
934                                     fn, line);
935                         fclose(fp);
936                         return -1;
937                 }
938
939                 if (0) {
940                         int i;
941
942                         fprintf(stderr, "ARGC = %d\n",argc);
943                         for (i = 0; i < argc; i++) {
944                                 fprintf(stderr, "\t%s\n", argv[i]);
945                         }
946                 }
947
948                 /*
949                  *      See if we need to import another dictionary.
950                  */
951                 if (strcasecmp(argv[0], "$INCLUDE") == 0) {
952                         if (my_dict_init(dir, argv[1], fn, line) < 0) {
953                                 fclose(fp);
954                                 return -1;
955                         }
956                         continue;
957                 } /* $INCLUDE */
958
959                 /*
960                  *      Perhaps this is an attribute.
961                  */
962                 if (strcasecmp(argv[0], "ATTRIBUTE") == 0) {
963                         if (process_attribute(fn, line, block_vendor,
964                                               argv + 1, argc - 1) == -1) {
965                                 fclose(fp);
966                                 return -1;
967                         }
968                         continue;
969                 }
970
971                 /*
972                  *      Process VALUE lines.
973                  */
974                 if (strcasecmp(argv[0], "VALUE") == 0) {
975                         if (process_value(fn, line,
976                                           argv + 1, argc - 1) == -1) {
977                                 fclose(fp);
978                                 return -1;
979                         }
980                         continue;
981                 }
982
983                 /*
984                  *      Process VENDOR lines.
985                  */
986                 if (strcasecmp(argv[0], "VENDOR") == 0) {
987                         if (process_vendor(fn, line,
988                                            argv + 1, argc - 1) == -1) {
989                                 fclose(fp);
990                                 return -1;
991                         }
992                         continue;
993                 }
994
995                 if (strcasecmp(argv[0], "BEGIN-VENDOR") == 0) {
996                         if (argc != 2) {
997                                 librad_log(
998                                 "dict_init: %s[%d] invalid BEGIN-VENDOR entry",
999                                         fn, line);
1000                                 fclose(fp);
1001                                 return -1;
1002                         }
1003
1004                         vendor = dict_vendorbyname(argv[1]);
1005                         if (!vendor) {
1006                                 librad_log(
1007                                         "dict_init: %s[%d]: unknown vendor %s",
1008                                         fn, line, argv[1]);
1009                                 fclose(fp);
1010                                 return -1;
1011                         }
1012                         block_vendor = vendor;
1013                         continue;
1014                 } /* BEGIN-VENDOR */
1015
1016                 if (strcasecmp(argv[0], "END-VENDOR") == 0) {
1017                         if (argc != 2) {
1018                                 librad_log(
1019                                 "dict_init: %s[%d] invalid END-VENDOR entry",
1020                                         fn, line);
1021                                 fclose(fp);
1022                                 return -1;
1023                         }
1024
1025                         vendor = dict_vendorbyname(argv[1]);
1026                         if (!vendor) {
1027                                 librad_log(
1028                                         "dict_init: %s[%d]: unknown vendor %s",
1029                                         fn, line, argv[1]);
1030                                 fclose(fp);
1031                                 return -1;
1032                         }
1033
1034                         if (vendor != block_vendor) {
1035                                 librad_log(
1036                                         "dict_init: %s[%d]: END-VENDOR %s does not match any previous BEGIN-VENDOR",
1037                                         fn, line, argv[1]);
1038                                 fclose(fp);
1039                                 return -1;
1040                         }
1041                         block_vendor = 0;
1042                         continue;
1043                 } /* END-VENDOR */
1044
1045                 /*
1046                  *      Any other string: We don't recognize it.
1047                  */
1048                 librad_log(
1049                         "dict_init: %s[%d] invalid keyword \"%s\"",
1050                         fn, line, argv[0]);
1051                 fclose(fp);
1052                 return -1;
1053         }
1054         fclose(fp);
1055         return 0;
1056 }
1057
1058 /*
1059  *      Initialize the directory, then fix the attr member of
1060  *      all attributes.
1061  */
1062 int dict_init(const char *dir, const char *fn)
1063 {
1064         /*
1065          *      Check if we need to change anything.  If not, don't do
1066          *      anything.
1067          */
1068         if (dict_stat_check(dir, fn)) {
1069                 return 0;
1070         }
1071
1072         /*
1073          *      Free the dictionaries, and the stat cache.
1074          */
1075         dict_free();
1076         stat_root_dir = strdup(dir);
1077         stat_root_file = strdup(fn);
1078
1079         /*
1080          *      Create the tree of vendor by name.   There MAY NOT
1081          *      be multiple vendors of the same name.
1082          *
1083          *      Each vendor is malloc'd, so the free function is free.
1084          */
1085         vendors_byname = lrad_hash_table_create(free);
1086         if (!vendors_byname) {
1087                 return -1;
1088         }
1089
1090         /*
1091          *      Create the tree of vendors by value.  There MAY
1092          *      be vendors of the same value.  If there are, we
1093          *      pick the latest one.
1094          */
1095         vendors_byvalue = lrad_hash_table_create(NULL);
1096         if (!vendors_byvalue) {
1097                 return -1;
1098         }
1099
1100         /*
1101          *      Create the tree of attributes by name.   There MAY NOT
1102          *      be multiple attributes of the same name.
1103          *
1104          *      Each attribute is malloc'd, so the free function is free.
1105          */
1106         attributes_byname = lrad_hash_table_create(free);
1107         if (!attributes_byname) {
1108                 return -1;
1109         }
1110
1111         /*
1112          *      Create the tree of attributes by value.  There MAY
1113          *      be attributes of the same value.  If there are, we
1114          *      pick the latest one.
1115          */
1116         attributes_byvalue = lrad_hash_table_create(NULL);
1117         if (!attributes_byvalue) {
1118                 return -1;
1119         }
1120
1121         values_byname = lrad_hash_table_create(free);
1122         if (!values_byname) {
1123                 return -1;
1124         }
1125
1126         values_byvalue = lrad_hash_table_create(NULL);
1127         if (!values_byvalue) {
1128                 return -1;
1129         }
1130
1131         value_fixup = NULL;     /* just to be safe. */
1132
1133         if (my_dict_init(dir, fn, NULL, 0) < 0)
1134                 return -1;
1135
1136         if (value_fixup) {
1137                 uint32_t hash;
1138                 DICT_ATTR *a;
1139                 value_fixup_t *this, *next;
1140
1141                 for (this = value_fixup; this != NULL; this = next) {
1142                         next = this->next;
1143
1144                         a = dict_attrbyname(this->attrstr);
1145                         if (!a) {
1146                                 librad_log(
1147                                         "dict_init: No ATTRIBUTE \"%s\" defined for VALUE \"%s\"",
1148                                         this->attrstr, this->dval->name);
1149                                 return -1; /* leak, but they should die... */
1150                         }
1151
1152                         this->dval->attr = a->attr;
1153
1154                         /*
1155                          *      Add the value into the dictionary.
1156                          */
1157                         hash = lrad_hash_update(&this->dval->attr,
1158                                                 sizeof(this->dval->attr),
1159                                                 this->hash);
1160                         if (!lrad_hash_table_insert(values_byname,
1161                                                     hash, this->dval)) {
1162                                 librad_log("dict_addvalue: Duplicate value name %s for attribute %s", this->dval->name, a->name);
1163                                 return -1;
1164                         }
1165                         
1166                         /*
1167                          *      Allow them to use the old name, but
1168                          *      prefer the new name when printing
1169                          *      values.
1170                          */
1171                         hash = lrad_hash(&this->dval->attr,
1172                                          sizeof(this->dval->attr));
1173                         hash = lrad_hash_update(&this->dval->value,
1174                                                 sizeof(this->dval->value),
1175                                                 hash);
1176                         if (!lrad_hash_table_finddata(values_byvalue, hash)) {
1177                                 lrad_hash_table_insert(values_byvalue,
1178                                                        hash, this->dval);
1179                         }
1180                         free(this);
1181
1182                         /*
1183                          *      Just so we don't lose track of things.
1184                          */
1185                         value_fixup = next;
1186                 }
1187         }
1188
1189         return 0;
1190 }
1191
1192 /*
1193  *      Get an attribute by its numerical value.
1194  */
1195 DICT_ATTR *dict_attrbyvalue(int val)
1196 {
1197         return lrad_hash_table_finddata(attributes_byvalue,
1198                                         lrad_hash(&val, sizeof(val)));
1199 }
1200
1201 /*
1202  *      Get an attribute by its name.
1203  */
1204 DICT_ATTR *dict_attrbyname(const char *name)
1205 {
1206         if (!name) return NULL;
1207
1208         return lrad_hash_table_finddata(attributes_byname,
1209                                         dict_hashname(name));
1210 }
1211
1212 /*
1213  *      Associate a value with an attribute and return it.
1214  */
1215 DICT_VALUE *dict_valbyattr(int attr, int val)
1216 {
1217         uint32_t hash = attr;
1218
1219         hash = lrad_hash_update(&val, sizeof(val), hash);
1220
1221         return lrad_hash_table_finddata(values_byvalue, hash);
1222 }
1223
1224 /*
1225  *      Get a value by its name, keyed off of an attribute.
1226  */
1227 DICT_VALUE *dict_valbyname(int attr, const char *name)
1228 {
1229         uint32_t hash;
1230
1231         if (!name) return NULL;
1232
1233         hash = dict_hashname(name);
1234         hash = lrad_hash_update(&attr, sizeof(attr), hash);
1235
1236         return lrad_hash_table_finddata(values_byname, hash);
1237 }
1238
1239 /*
1240  *      Get the vendor PEC based on the vendor name
1241  *
1242  *      This is efficient only for small numbers of vendors.
1243  */
1244 int dict_vendorbyname(const char *name)
1245 {
1246         uint32_t hash;
1247         DICT_VENDOR     *dv;
1248
1249         if (!name) return 0;
1250
1251         hash = dict_hashname(name);
1252         
1253         dv = lrad_hash_table_finddata(vendors_byname, hash);
1254         if (!dv) return 0;
1255
1256         return dv->vendorpec;
1257 }
1258
1259 /*
1260  *      Return the vendor struct based on the PEC.
1261  */
1262 DICT_VENDOR *dict_vendorbyvalue(int vendor)
1263 {
1264         return lrad_hash_table_finddata(vendors_byvalue,
1265                                         lrad_hash(&vendor, sizeof(vendor)));
1266 }