Port dictionary file sanity checks from the head
[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) == 0) {
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         lrad_hash_table_insert(vendors_byvalue, dv->vendorpec, dv);
289
290         return 0;
291 }
292
293 /*
294  *      Add an attribute to the dictionary.
295  */
296 int dict_addattr(const char *name, int vendor, int type, int value,
297                  ATTR_FLAGS flags)
298 {
299         static int      max_attr = 0;
300         uint32_t        hash;
301         DICT_ATTR       *attr;
302
303         if (strlen(name) > (sizeof(attr->name) -1)) {
304                 librad_log("dict_addattr: attribute name too long");
305                 return -1;
306         }
307
308         /*
309          *      If the value is '-1', that means use a pre-existing
310          *      one (if it already exists).  If one does NOT already exist,
311          *      then create a new attribute, with a non-conflicting value,
312          *      and use that.
313          */
314         if (value == -1) {
315                 if (dict_attrbyname(name)) {
316                         return 0; /* exists, don't add it again */
317                 }
318
319                 value = ++max_attr;
320
321         } else if (vendor == 0) {
322                 /*
323                  *  Update 'max_attr'
324                  */
325                 if (value > max_attr) {
326                         max_attr = value;
327                 }
328         }
329
330         if (value < 0) {
331                 librad_log("dict_addattr: ATTRIBUTE has invalid number (less than zero)");
332                 return -1;
333         }
334
335         if (value >= 65536) {
336                 librad_log("dict_addattr: ATTRIBUTE has invalid number (larger than 65535).");
337                 return -1;
338         }
339
340         if (vendor) {
341                 DICT_VENDOR *dv = dict_vendorbyvalue(vendor);
342
343                 /*
344                  *      If the vendor isn't defined, die/
345                  */
346                 if (!dv) {
347                         librad_log("dict_addattr: Unknown vendor");
348                         return -1;
349                 }
350
351                 /*
352                  *      With a few exceptions, attributes can only be
353                  *      1..255.  The check above catches the less than
354                  *      zero case.
355                  */
356                 if ((dv->type == 1) && (value >= 256)) {
357                         librad_log("dict_addattr: ATTRIBUTE has invalid number (larger than 255).");
358                         return -1;
359                 } /* else 256..65535 are allowed */
360         }
361
362         /*
363          *      Create a new attribute for the list
364          */
365         if ((attr = malloc(sizeof(*attr))) == NULL) {
366                 librad_log("dict_addattr: out of memory");
367                 return -1;
368         }
369
370         hash = dict_hashname(name);
371         strcpy(attr->name, name);
372         attr->attr = value;
373         attr->attr |= (vendor << 16); /* FIXME: hack */
374         attr->type = type;
375         attr->flags = flags;
376         attr->vendor = vendor;
377
378
379         /*
380          *      Insert the attribute, only if it's not a duplicate.
381          */
382         if (lrad_hash_table_insert(attributes_byname, hash, attr) == 0) {
383                 DICT_ATTR       *a;
384
385                 /*
386                  *      If the attribute has identical number, then
387                  *      ignore the duplicate.
388                  */
389                 a = lrad_hash_table_finddata(attributes_byname, hash);
390                 if (a && (strcasecmp(a->name, attr->name) == 0)) {
391                         if (a->attr != attr->attr) {
392                                 librad_log("dict_addattr: Duplicate attribute name %s", name);
393                                 return -1;
394                         }
395
396                         /*
397                          *      Same name, same vendor, same attr,
398                          *      maybe the flags and/or type is
399                          *      different.  Let the new value
400                          *      over-ride the old one.
401                          */
402                 }
403         }
404
405         /*
406          *      Insert the SAME pointer (not free'd when this tree is
407          *      deleted), into another tree.
408          *
409          *      If the newly inserted entry is a duplicate of an existing
410          *      entry, then the old entry is tossed, and the new one
411          *      replaces it.  This behaviour is configured in the
412          *      lrad_hash_table_create() function.
413          *
414          *      We want this behaviour because we want OLD names for
415          *      the attributes to be read from the configuration
416          *      files, but when we're printing them, (and looking up
417          *      by value) we want to use the NEW name.
418          */
419         lrad_hash_table_insert(attributes_byvalue, (uint32_t) attr->attr, attr);
420
421         return 0;
422 }
423
424
425 /*
426  *      Add a value for an attribute to the dictionary.
427  */
428 int dict_addvalue(const char *namestr, const char *attrstr, int value)
429 {
430         size_t          length;
431         DICT_ATTR       *dattr;
432         uint32_t        hash;
433         DICT_VALUE      *dval;
434
435         if ((length = strlen(namestr)) >= DICT_VALUE_MAX_NAME_LEN) {
436                 librad_log("dict_addvalue: value name too long");
437                 return -1;
438         }
439
440         if ((dval = malloc(sizeof(*dval) + length)) == NULL) {
441                 librad_log("dict_addvalue: out of memory");
442                 return -1;
443         }
444         memset(dval, 0, sizeof(*dval));
445
446         hash = dict_hashname(namestr);
447         strcpy(dval->name, namestr);
448         dval->value = value;
449
450         /*
451          *      Remember which attribute is associated with this
452          *      value, if possible.
453          */
454         dattr = dict_attrbyname(attrstr);
455         if (dattr) {
456                 dval->attr = dattr->attr;
457                 hash = lrad_hash_update(&dval->attr, sizeof(dval->attr), hash);
458         } else {
459                 value_fixup_t *fixup;
460                 
461                 fixup = (value_fixup_t *) malloc(sizeof(*fixup));
462                 if (!fixup) {
463                         librad_log("dict_addvalue: out of memory");
464                         return -1;
465                 }
466                 memset(fixup, 0, sizeof(*fixup));
467
468                 strNcpy(fixup->attrstr, attrstr, sizeof(fixup->attrstr));
469                 fixup->hash = hash;
470                 fixup->dval = dval;
471                 
472                 /*
473                  *      Insert to the head of the list.
474                  */
475                 fixup->next = value_fixup;
476                 value_fixup = fixup;
477
478                 return 0;
479         }
480
481         /*
482          *      Add the value into the dictionary.
483          */
484         if (lrad_hash_table_insert(values_byname, hash, dval) == 0) {
485                 if (dattr) {
486                         DICT_VALUE *old;
487                         
488                         /*
489                          *      Suppress duplicates with the same
490                          *      name and value.  There are lots in
491                          *      dictionary.ascend.
492                          */
493                         old = dict_valbyname(dattr->attr, namestr);
494                         if (old && (old->value == dval->value)) {
495                                 free(dval);
496                                 return 0;
497                         }
498                 }
499
500                 librad_log("dict_addvalue: Duplicate value name %s for attribute %s", namestr, attrstr);
501                 return -1;
502         }
503
504         /*
505          *      There are multiple VALUE's, keyed by attribute, so we
506          *      take care of that here.
507          */
508         hash = dval->attr;
509         hash = lrad_hash_update(&dval->value, sizeof(dval->value), hash);
510         lrad_hash_table_insert(values_byvalue, hash, dval);
511
512         return 0;
513 }
514
515 /*
516  *      Process the ATTRIBUTE command
517  */
518 static int process_attribute(const char* fn, const int line,
519                              const int block_vendor, char **argv,
520                              int argc)
521 {
522         int             vendor = 0;
523         int             value;
524         int             type;
525         char            *s, *c;
526         ATTR_FLAGS      flags;
527
528         if ((argc < 3) || (argc > 4)) {
529                 librad_log("dict_init: %s[%d]: invalid ATTRIBUTE line",
530                         fn, line);
531                 return -1;
532         }
533
534         /*
535          *      Validate all entries
536          */
537         if (!isdigit((int) argv[1][0])) {
538                 librad_log("dict_init: %s[%d]: invalid value", fn, line);
539                 return -1;
540         }
541         sscanf(argv[1], "%i", &value);
542
543         /*
544          *      find the type of the attribute.
545          */
546         type = lrad_str2int(type_table, argv[2], -1);
547         if (type < 0) {
548                 librad_log("dict_init: %s[%d]: invalid type \"%s\"",
549                         fn, line, argv[2]);
550                 return -1;
551         }
552
553         /*
554          *      Only look up the vendor if the string
555          *      is non-empty.
556          */
557         memset(&flags, 0, sizeof(flags));
558         if (argc == 4) {
559                 s = strtok(argv[3], ",");
560                 while (s) {
561                         if (strcmp(s, "has_tag") == 0 ||
562                             strcmp(s, "has_tag=1") == 0) {
563                                 /* Boolean flag, means this is a
564                                    tagged attribute */
565                                 flags.has_tag = 1;
566                                 
567                         } else if (strncmp(s, "encrypt=", 8) == 0) {
568                                 /* Encryption method, defaults to 0 (none).
569                                    Currently valid is just type 2,
570                                    Tunnel-Password style, which can only
571                                    be applied to strings. */
572                                 flags.encrypt = strtol(s + 8, &c, 0);
573                                 if (*c) {
574                                         librad_log( "dict_init: %s[%d] invalid option %s",
575                                                     fn, line, s);
576                                         return -1;
577                                 }
578                         } else {
579                                 /* Must be a vendor 'flag'... */
580                                 if (strncmp(s, "vendor=", 7) == 0) {
581                                         /* New format */
582                                         s += 7;
583                                 }
584                                 
585                                 vendor = dict_vendorbyname(s);
586                                 if (!vendor) {
587                                         librad_log( "dict_init: %s[%d]: unknown vendor %s",
588                                                     fn, line, s);
589                                         return -1;
590                                 }
591                                 if (block_vendor && argv[3][0] &&
592                                     (block_vendor != vendor)) {
593                                         librad_log("dict_init: %s[%d]: mismatched vendor %s within BEGIN-VENDOR/END-VENDOR block",
594                                                    fn, line, argv[3]);
595                                         return -1;
596                                 }
597                         }
598                         s = strtok(NULL, ",");
599                 }
600         }
601
602         if (block_vendor) vendor = block_vendor;
603
604         /*
605          *      Special checks for tags, they make our life much more
606          *      difficult.
607          */
608         if (flags.has_tag) {
609                 /*
610                  *      VSA's can't be tagged.
611                  */
612                 if (vendor) {
613                         librad_log("dict_init: %s[%d]: Vendor attributes cannot be tagged.",
614                                    fn, line);
615                         return -1;
616                 }
617
618                 /*
619                  *      Only string, octets, and integer can be tagged.
620                  */
621                 switch (type) {
622                 case PW_TYPE_STRING:
623                 case PW_TYPE_INTEGER:
624                         break;
625
626                 default:
627                         librad_log("dict_init: %s[%d]: Attributes of type %s cannot be tagged.",
628                                    fn, line,
629                                    lrad_int2str(type_table, type, "?Unknown?"));
630                         return -1;
631                         
632                 }
633         }
634
635         /*
636          *      Add it in.
637          */
638         if (dict_addattr(argv[0], vendor, type, value, flags) < 0) {
639                 librad_log("dict_init: %s[%d]: %s",
640                            fn, line, librad_errstr);
641                 return -1;
642         }
643
644         return 0;
645 }
646
647
648 /*
649  *      Process the VALUE command
650  */
651 static int process_value(const char* fn, const int line, char **argv,
652                          int argc)
653 {
654         int     value;
655
656         if (argc != 3) {
657                 librad_log("dict_init: %s[%d]: invalid VALUE line",
658                         fn, line);
659                 return -1;
660         }
661         /*
662          *      For Compatibility, skip "Server-Config"
663          */
664         if (strcasecmp(argv[0], "Server-Config") == 0)
665                 return 0;
666
667         /*
668          *      Validate all entries
669          */
670         if (!isdigit((int) argv[2][0])) {
671                 librad_log("dict_init: %s[%d]: invalid value",
672                         fn, line);
673                 return -1;
674         }
675         sscanf(argv[2], "%i", &value);
676
677         /*
678          *      valuepair.c will get excited when creating attributes,
679          *      if it sees values which look like integers, so we can't
680          *      use them here.
681          */
682         if (isdigit(argv[1][0])) {
683                 librad_log("dict_init: %s[%d]: Names for VALUEs cannot start with a digit.",
684                            fn, line);
685         }
686         
687         if (dict_addvalue(argv[1], argv[0], value) < 0) {
688                 librad_log("dict_init: %s[%d]: %s",
689                            fn, line, librad_errstr);
690                 return -1;
691         }
692
693         return 0;
694 }
695
696
697 /*
698  *      Process the VENDOR command
699  */
700 static int process_vendor(const char* fn, const int line, char **argv,
701                           int argc)
702 {
703         int     value;
704         const   char *format = NULL;
705
706         if ((argc < 2) || (argc > 3)) {
707                 librad_log( "dict_init: %s[%d] invalid VENDOR entry",
708                             fn, line);
709                 return -1;
710         }
711
712         /*
713          *       Validate all entries
714          */
715         if (!isdigit((int) argv[1][0])) {
716                 librad_log("dict_init: %s[%d]: invalid value",
717                         fn, line);
718                 return -1;
719         }
720         value = atoi(argv[1]);
721
722         /* Create a new VENDOR entry for the list */
723         if (dict_addvendor(argv[0], value) < 0) {
724                 librad_log("dict_init: %s[%d]: %s",
725                            fn, line, librad_errstr);
726                 return -1;
727         }
728
729         /*
730          *      Look for a format statement
731          */
732         if (argc == 3) {
733                 format = argv[2];
734
735         } else if (value == VENDORPEC_USR) { /* catch dictionary screw-ups */
736                 format = "format=4,0";
737
738         } else if (value == VENDORPEC_LUCENT) {
739                 format = "format=2,1";
740
741         } else if (value == VENDORPEC_STARENT) {
742                 format = "format=2,2";
743
744         } /* else no fixups to do */
745
746         if (format) {
747                 int type, length;
748                 const char *p;
749                 DICT_VENDOR *dv;
750
751                 if (strncasecmp(format, "format=", 7) != 0) {
752                         librad_log("dict_init: %s[%d]: Invalid format for VENDOR.  Expected \"format=\", got \"%s\"",
753                                    fn, line, format);
754                         return -1;
755                 }
756
757                 p = format + 7;
758                 if ((strlen(p) != 3) || 
759                     !isdigit((int) p[0]) ||
760                     (p[1] != ',') ||
761                     !isdigit((int) p[2])) {
762                         librad_log("dict_init: %s[%d]: Invalid format for VENDOR.  Expected text like \"1,1\", got \"%s\"",
763                                    fn, line, p);
764                         return -1;
765                 }
766
767                 type = (int) (p[0] - '0');
768                 length = (int) (p[2] - '0');
769
770                 dv = dict_vendorbyvalue(value);
771                 if (!dv) {
772                         librad_log("dict_init: %s[%d]: Failed adding format for VENDOR",
773                                    fn, line);
774                         return -1;
775                 }
776
777                 if ((type != 1) && (type != 2) && (type != 4)) {
778                         librad_log("dict_init: %s[%d]: invalid type value %d for VENDOR",
779                                    fn, line, type);
780                         return -1;
781                 }
782
783                 if ((length != 0) && (length != 1) && (length != 2)) {
784                         librad_log("dict_init: %s[%d]: invalid length value %d for VENDOR",
785                                    fn, line, length);
786                         return -1;
787                 }
788
789                 dv->type = type;
790                 dv->length = length;
791         }
792
793         return 0;
794 }
795
796 /*
797  *      String split routine.  Splits an input string IN PLACE
798  *      into pieces, based on spaces.
799  */
800 static int str2argv(char *str, char **argv, int max_argc)
801 {
802         int argc = 0;
803
804         while (*str) {
805                 if (argc >= max_argc) return argc;
806
807                 /*
808                  *      Chop out comments early.
809                  */
810                 if (*str == '#') {
811                         *str = '\0';
812                         break;
813                 }
814
815                 while ((*str == ' ') ||
816                        (*str == '\t') ||
817                        (*str == '\r') ||
818                        (*str == '\n')) *(str++) = '\0';
819
820                 if (!*str) return argc;
821
822                 argv[argc] = str;
823                 argc++;
824
825                 while (*str &&
826                        (*str != ' ') &&
827                        (*str != '\t') &&
828                        (*str != '\r') &&
829                        (*str != '\n')) str++;
830         }
831
832         return argc;
833 }
834
835 #define MAX_ARGV (16)
836
837 /*
838  *      Initialize the dictionary.
839  */
840 static int my_dict_init(const char *dir, const char *fn,
841                         const char *src_file, int src_line)
842 {
843         FILE    *fp;
844         char    dirtmp[256];
845         char    buf[256];
846         char    *p;
847         int     line = 0;
848         int     vendor;
849         int     block_vendor;
850         struct stat statbuf;
851         char    *argv[MAX_ARGV];
852         int     argc;
853
854         if (strlen(fn) >= sizeof(dirtmp) / 2 ||
855             strlen(dir) >= sizeof(dirtmp) / 2) {
856                 librad_log("dict_init: filename name too long");
857                 return -1;
858         }
859
860         /*
861          *      First see if fn is relative to dir. If so, create
862          *      new filename. If not, remember the absolute dir.
863          */
864         if ((p = strrchr(fn, '/')) != NULL) {
865                 strcpy(dirtmp, fn);
866                 dirtmp[p - fn] = 0;
867                 dir = dirtmp;
868         } else if (dir && dir[0] && strcmp(dir, ".") != 0) {
869                 snprintf(dirtmp, sizeof(dirtmp), "%s/%s", dir, fn);
870                 fn = dirtmp;
871         }
872
873         if ((fp = fopen(fn, "r")) == NULL) {
874                 if (!src_file) {
875                         librad_log("dict_init: Couldn't open dictionary \"%s\": %s",
876                                    fn, strerror(errno));
877                 } else {
878                         librad_log("dict_init: %s[%d]: Couldn't open dictionary \"%s\": %s",
879                                    src_file, src_line, fn, strerror(errno));
880                 }
881                 return -1;
882         }
883
884         stat(fn, &statbuf); /* fopen() guarantees this will succeed */
885         if (!S_ISREG(statbuf.st_mode)) {
886                 fclose(fp);
887                 librad_log("dict_init: Dictionary \"%s\" is not a regular file",
888                            fn);
889                 return -1;        
890         }
891         dict_stat_add(fn, &statbuf);
892
893         /*
894          *      Seed the random pool with data.
895          */
896         lrad_rand_seed(&statbuf, sizeof(statbuf));
897
898         block_vendor = 0;
899
900         while (fgets(buf, sizeof(buf), fp) != NULL) {
901                 line++;
902                 if (buf[0] == '#' || buf[0] == 0 ||
903                     buf[0] == '\n' || buf[0] == '\r')
904                         continue;
905
906                 /*
907                  *  Comment characters should NOT be appearing anywhere but
908                  *  as start of a comment;
909                  */
910                 p = strchr(buf, '#');
911                 if (p) *p = '\0';
912
913                 argc = str2argv(buf, argv, MAX_ARGV);
914                 if (argc == 0) continue;
915
916                 if (argc == 1) {
917                         librad_log( "dict_init: %s[%d] invalid entry",
918                                     fn, line);
919                         fclose(fp);
920                         return -1;
921                 }
922
923                 if (0) {
924                         int i;
925
926                         fprintf(stderr, "ARGC = %d\n",argc);
927                         for (i = 0; i < argc; i++) {
928                                 fprintf(stderr, "\t%s\n", argv[i]);
929                         }
930                 }
931
932                 /*
933                  *      See if we need to import another dictionary.
934                  */
935                 if (strcasecmp(argv[0], "$INCLUDE") == 0) {
936                         if (my_dict_init(dir, argv[1], fn, line) < 0) {
937                                 fclose(fp);
938                                 return -1;
939                         }
940                         continue;
941                 } /* $INCLUDE */
942
943                 /*
944                  *      Perhaps this is an attribute.
945                  */
946                 if (strcasecmp(argv[0], "ATTRIBUTE") == 0) {
947                         if (process_attribute(fn, line, block_vendor,
948                                               argv + 1, argc - 1) == -1) {
949                                 fclose(fp);
950                                 return -1;
951                         }
952                         continue;
953                 }
954
955                 /*
956                  *      Process VALUE lines.
957                  */
958                 if (strcasecmp(argv[0], "VALUE") == 0) {
959                         if (process_value(fn, line,
960                                           argv + 1, argc - 1) == -1) {
961                                 fclose(fp);
962                                 return -1;
963                         }
964                         continue;
965                 }
966
967                 /*
968                  *      Process VENDOR lines.
969                  */
970                 if (strcasecmp(argv[0], "VENDOR") == 0) {
971                         if (process_vendor(fn, line,
972                                            argv + 1, argc - 1) == -1) {
973                                 fclose(fp);
974                                 return -1;
975                         }
976                         continue;
977                 }
978
979                 if (strcasecmp(argv[0], "BEGIN-VENDOR") == 0) {
980                         if (argc != 2) {
981                                 librad_log(
982                                 "dict_init: %s[%d] invalid BEGIN-VENDOR entry",
983                                         fn, line);
984                                 fclose(fp);
985                                 return -1;
986                         }
987
988                         vendor = dict_vendorbyname(argv[1]);
989                         if (!vendor) {
990                                 librad_log(
991                                         "dict_init: %s[%d]: unknown vendor %s",
992                                         fn, line, argv[1]);
993                                 fclose(fp);
994                                 return -1;
995                         }
996                         block_vendor = vendor;
997                         continue;
998                 } /* BEGIN-VENDOR */
999
1000                 if (strcasecmp(argv[0], "END-VENDOR") == 0) {
1001                         if (argc != 2) {
1002                                 librad_log(
1003                                 "dict_init: %s[%d] invalid END-VENDOR entry",
1004                                         fn, line);
1005                                 fclose(fp);
1006                                 return -1;
1007                         }
1008
1009                         vendor = dict_vendorbyname(argv[1]);
1010                         if (!vendor) {
1011                                 librad_log(
1012                                         "dict_init: %s[%d]: unknown vendor %s",
1013                                         fn, line, argv[1]);
1014                                 fclose(fp);
1015                                 return -1;
1016                         }
1017
1018                         if (vendor != block_vendor) {
1019                                 librad_log(
1020                                         "dict_init: %s[%d]: END-VENDOR %s does not match any previous BEGIN-VENDOR",
1021                                         fn, line, argv[1]);
1022                                 fclose(fp);
1023                                 return -1;
1024                         }
1025                         block_vendor = 0;
1026                         continue;
1027                 } /* END-VENDOR */
1028
1029                 /*
1030                  *      Any other string: We don't recognize it.
1031                  */
1032                 librad_log(
1033                         "dict_init: %s[%d] invalid keyword \"%s\"",
1034                         fn, line, argv[0]);
1035                 fclose(fp);
1036                 return -1;
1037         }
1038         fclose(fp);
1039         return 0;
1040 }
1041
1042 /*
1043  *      Initialize the directory, then fix the attr member of
1044  *      all attributes.
1045  */
1046 int dict_init(const char *dir, const char *fn)
1047 {
1048         /*
1049          *      Check if we need to change anything.  If not, don't do
1050          *      anything.
1051          */
1052         if (dict_stat_check(dir, fn)) {
1053                 return 0;
1054         }
1055
1056         /*
1057          *      Free the dictionaries, and the stat cache.
1058          */
1059         dict_free();
1060         stat_root_dir = strdup(dir);
1061         stat_root_file = strdup(fn);
1062
1063         /*
1064          *      Create the tree of vendor by name.   There MAY NOT
1065          *      be multiple vendors of the same name.
1066          *
1067          *      Each vendor is malloc'd, so the free function is free.
1068          */
1069         vendors_byname = lrad_hash_table_create(8, free, 0);
1070         if (!vendors_byname) {
1071                 return -1;
1072         }
1073
1074         /*
1075          *      Create the tree of vendors by value.  There MAY
1076          *      be vendors of the same value.  If there are, we
1077          *      pick the latest one.
1078          */
1079         vendors_byvalue = lrad_hash_table_create(8, NULL, 1);
1080         if (!vendors_byvalue) {
1081                 return -1;
1082         }
1083
1084         /*
1085          *      Create the tree of attributes by name.   There MAY NOT
1086          *      be multiple attributes of the same name.
1087          *
1088          *      Each attribute is malloc'd, so the free function is free.
1089          */
1090         attributes_byname = lrad_hash_table_create(11, free, 0);
1091         if (!attributes_byname) {
1092                 return -1;
1093         }
1094
1095         /*
1096          *      Create the tree of attributes by value.  There MAY
1097          *      be attributes of the same value.  If there are, we
1098          *      pick the latest one.
1099          */
1100         attributes_byvalue = lrad_hash_table_create(11, NULL, 1);
1101         if (!attributes_byvalue) {
1102                 return -1;
1103         }
1104
1105         values_byname = lrad_hash_table_create(11, free, 0);
1106         if (!values_byname) {
1107                 return -1;
1108         }
1109
1110         values_byvalue = lrad_hash_table_create(11, NULL, 1);
1111         if (!values_byvalue) {
1112                 return -1;
1113         }
1114
1115         value_fixup = NULL;     /* just to be safe. */
1116
1117         if (my_dict_init(dir, fn, NULL, 0) < 0)
1118                 return -1;
1119
1120         if (value_fixup) {
1121                 uint32_t hash;
1122                 DICT_ATTR *a;
1123                 value_fixup_t *this, *next;
1124
1125                 for (this = value_fixup; this != NULL; this = next) {
1126                         next = this->next;
1127
1128                         a = dict_attrbyname(this->attrstr);
1129                         if (!a) {
1130                                 librad_log(
1131                                         "dict_init: No ATTRIBUTE \"%s\" defined for VALUE \"%s\"",
1132                                         this->attrstr, this->dval->name);
1133                                 return -1; /* leak, but they should die... */
1134                         }
1135
1136                         this->dval->attr = a->attr;
1137
1138                         /*
1139                          *      Add the value into the dictionary.
1140                          */
1141                         hash = lrad_hash_update(&this->dval->attr,
1142                                                 sizeof(this->dval->attr),
1143                                                 this->hash);
1144                         if (lrad_hash_table_insert(values_byname,
1145                                                    hash, this->dval) == 0) {
1146                                 librad_log("dict_addvalue: Duplicate value name %s for attribute %s", this->dval->name, a->name);
1147                                 return -1;
1148                         }
1149                         
1150                         /*
1151                          *      Allow them to use the old name, but
1152                          *      prefer the new name when printing
1153                          *      values.
1154                          */
1155                         hash = (uint32_t) this->dval->attr;
1156                         hash = lrad_hash_update(&this->dval->value,
1157                                                 sizeof(this->dval->value),
1158                                                 hash);
1159                         if (!lrad_hash_table_finddata(values_byvalue, hash)) {
1160                                 lrad_hash_table_insert(values_byvalue,
1161                                                        hash, this->dval);
1162                         }
1163                         free(this);
1164
1165                         /*
1166                          *      Just so we don't lose track of things.
1167                          */
1168                         value_fixup = next;
1169                 }
1170         }
1171
1172         return 0;
1173 }
1174
1175 /*
1176  *      Get an attribute by its numerical value.
1177  */
1178 DICT_ATTR *dict_attrbyvalue(int val)
1179 {
1180         return lrad_hash_table_finddata(attributes_byvalue, (uint32_t) val);
1181 }
1182
1183 /*
1184  *      Get an attribute by its name.
1185  */
1186 DICT_ATTR *dict_attrbyname(const char *name)
1187 {
1188         if (!name) return NULL;
1189
1190         return lrad_hash_table_finddata(attributes_byname,
1191                                         dict_hashname(name));
1192 }
1193
1194 /*
1195  *      Associate a value with an attribute and return it.
1196  */
1197 DICT_VALUE *dict_valbyattr(int attr, int val)
1198 {
1199         uint32_t hash = attr;
1200
1201         hash = lrad_hash_update(&val, sizeof(val), hash);
1202
1203         return lrad_hash_table_finddata(values_byvalue, hash);
1204 }
1205
1206 /*
1207  *      Get a value by its name, keyed off of an attribute.
1208  */
1209 DICT_VALUE *dict_valbyname(int attr, const char *name)
1210 {
1211         uint32_t hash;
1212
1213         if (!name) return NULL;
1214
1215         hash = dict_hashname(name);
1216         hash = lrad_hash_update(&attr, sizeof(attr), hash);
1217
1218         return lrad_hash_table_finddata(values_byname, hash);
1219 }
1220
1221 /*
1222  *      Get the vendor PEC based on the vendor name
1223  *
1224  *      This is efficient only for small numbers of vendors.
1225  */
1226 int dict_vendorbyname(const char *name)
1227 {
1228         uint32_t hash;
1229         DICT_VENDOR     *dv;
1230
1231         if (!name) return 0;
1232
1233         hash = dict_hashname(name);
1234         
1235         dv = lrad_hash_table_finddata(vendors_byname, hash);
1236         if (!dv) return 0;
1237
1238         return dv->vendorpec;
1239 }
1240
1241 /*
1242  *      Return the vendor struct based on the PEC.
1243  */
1244 DICT_VENDOR *dict_vendorbyvalue(int vendor)
1245 {
1246         return lrad_hash_table_finddata(vendors_byvalue, (uint32_t) vendor);
1247 }