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