Signed / unsigned fixes and function prototypes
[freeradius.git] / src / lib / valuepair.c
1 /*
2  * valuepair.c  Functions to handle VALUE_PAIRs
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,2006  The FreeRADIUS server project
21  */
22
23 #include <freeradius-devel/ident.h>
24 RCSID("$Id$")
25
26 #include        <freeradius-devel/libradius.h>
27
28 #include        <ctype.h>
29
30 #ifdef HAVE_MALLOC_H
31 #  include      <malloc.h>
32 #endif
33
34 #ifdef HAVE_REGEX_H
35 #  include      <regex.h>
36 #endif
37
38 static const char *months[] = {
39         "jan", "feb", "mar", "apr", "may", "jun",
40         "jul", "aug", "sep", "oct", "nov", "dec" };
41
42 /*
43  *      This padding is necessary only for attributes that are NOT
44  *      in the dictionary, and then only because the rest of the
45  *      code accesses vp->name directly, rather than through an
46  *      accessor function.
47  *
48  *      The name padding only has to large enough for:
49  *
50  *              Vendor-65535-Attr-65535
51  *
52  *      i.e. 23 characters, plus a zero.  We add another 8 bytes for
53  *      padding, because the VALUE_PAIR structure may be un-aligned.
54  *
55  *      The result is that for the normal case, the server uses a less
56  *      memory (36 bytes * number of VALUE_PAIRs).
57  */
58 #define FR_VP_NAME_PAD (32)
59 #define FR_VP_NAME_LEN (24)
60
61 VALUE_PAIR *pairalloc(DICT_ATTR *da)
62 {
63         size_t name_len = 0;
64         VALUE_PAIR *vp;
65
66         /*
67          *      Not in the dictionary: the name is allocated AFTER
68          *      the VALUE_PAIR struct.
69          */
70         if (!da) name_len = FR_VP_NAME_PAD;
71
72         vp = malloc(sizeof(*vp) + name_len);
73         if (!vp) return NULL;
74         memset(vp, 0, sizeof(*vp));
75
76         if (da) {
77                 vp->attribute = da->attr;
78                 vp->vendor = da->vendor;
79                 vp->type = da->type;
80                 vp->name = da->name;
81                 vp->flags = da->flags;
82         } else {
83                 vp->attribute = 0;
84                 vp->vendor = 0;
85                 vp->type = PW_TYPE_OCTETS;
86                 vp->name = NULL;
87                 memset(&vp->flags, 0, sizeof(vp->flags));
88                 vp->flags.unknown_attr = 1;
89         }
90
91         switch (vp->type) {
92                 case PW_TYPE_BYTE:
93                         vp->length = 1;
94                         break;
95
96                 case PW_TYPE_SHORT:
97                         vp->length = 2;
98                         break;
99
100                 case PW_TYPE_INTEGER:
101                 case PW_TYPE_IPADDR:
102                 case PW_TYPE_DATE:
103                 case PW_TYPE_SIGNED:
104                         vp->length = 4;
105                         break;
106
107                 case PW_TYPE_IFID:
108                         vp->length = sizeof(vp->vp_ifid);
109                         break;
110
111                 case PW_TYPE_IPV6ADDR:
112                         vp->length = sizeof(vp->vp_ipv6addr);
113                         break;
114
115                 case PW_TYPE_IPV6PREFIX:
116                         vp->length = sizeof(vp->vp_ipv6prefix);
117                         break;
118
119                 case PW_TYPE_ETHERNET:
120                         vp->length = sizeof(vp->vp_ether);
121                         break;
122
123                 case PW_TYPE_TLV:
124                         vp->vp_tlv = NULL;
125                         vp->length = 0;
126                         break;
127
128                 case PW_TYPE_COMBO_IP:
129                 default:
130                         vp->length = 0;
131                         break;
132         }
133
134         return vp;
135 }
136
137 /*
138  *      Create a new valuepair.
139  */
140 VALUE_PAIR *paircreate_raw(int attr, int vendor, int type, VALUE_PAIR *vp)
141 {
142         char *p = (char *) (vp + 1);
143
144         if (!vp->flags.unknown_attr) {
145                 pairfree(&vp);
146                 return NULL;
147         }
148
149         vp->vendor = vendor;
150         vp->attribute = attr;
151         vp->operator = T_OP_EQ;
152         vp->name = p;
153         vp->type = type;
154         vp->length = 0;
155         memset(&vp->flags, 0, sizeof(vp->flags));
156         vp->flags.unknown_attr = 1;
157         
158         if (!vp_print_name(p, FR_VP_NAME_LEN, vp->attribute, vp->vendor)) {
159                 free(vp);
160                 return NULL;
161         }
162
163         return vp;
164 }
165
166 /*
167  *      Create a new valuepair.
168  */
169 VALUE_PAIR *paircreate(int attr, int vendor, int type)
170 {
171         VALUE_PAIR      *vp;
172         DICT_ATTR       *da;
173
174         da = dict_attrbyvalue(attr, vendor);
175         if ((vp = pairalloc(da)) == NULL) {
176                 fr_strerror_printf("out of memory");
177                 return NULL;
178         }
179         vp->operator = T_OP_EQ;
180
181         /*
182          *      It isn't in the dictionary: update the name.
183          */
184         if (!da) return paircreate_raw(attr, vendor, type, vp);
185
186         return vp;
187 }
188
189 /*
190  *      release the memory used by a single attribute-value pair
191  *      just a wrapper around free() for now.
192  */
193 void pairbasicfree(VALUE_PAIR *pair)
194 {
195         if (pair->type == PW_TYPE_TLV) free(pair->vp_tlv);
196         /* clear the memory here */
197         memset(pair, 0, sizeof(*pair));
198         free(pair);
199 }
200
201 /*
202  *      Release the memory used by a list of attribute-value
203  *      pairs, and sets the pair pointer to NULL.
204  */
205 void pairfree(VALUE_PAIR **pair_ptr)
206 {
207         VALUE_PAIR      *next, *pair;
208
209         if (!pair_ptr) return;
210         pair = *pair_ptr;
211
212         while (pair != NULL) {
213                 next = pair->next;
214                 pairbasicfree(pair);
215                 pair = next;
216         }
217
218         *pair_ptr = NULL;
219 }
220
221
222 /*
223  *      Find the pair with the matching attribute
224  */
225 VALUE_PAIR * pairfind(VALUE_PAIR *first, unsigned int attr, unsigned int vendor)
226 {
227         while (first) {
228                 if ((first->attribute == attr) && (first->vendor == vendor)) {
229                         return first;
230                 }
231                 first = first->next;
232         }
233
234         return NULL;
235 }
236
237
238 /*
239  *      Delete the pair(s) with the matching attribute
240  */
241 void pairdelete(VALUE_PAIR **first, unsigned int attr, unsigned int vendor)
242 {
243         VALUE_PAIR *i, *next;
244         VALUE_PAIR **last = first;
245
246         for(i = *first; i; i = next) {
247                 next = i->next;
248                 if ((i->attribute == attr) && (i->vendor == vendor)) {
249                         *last = next;
250                         pairbasicfree(i);
251                 } else {
252                         last = &i->next;
253                 }
254         }
255 }
256
257 /*
258  *      Add a pair at the end of a VALUE_PAIR list.
259  */
260 void pairadd(VALUE_PAIR **first, VALUE_PAIR *add)
261 {
262         VALUE_PAIR *i;
263
264         if (!add) return;
265
266         if (*first == NULL) {
267                 *first = add;
268                 return;
269         }
270         for(i = *first; i->next; i = i->next)
271                 ;
272         i->next = add;
273 }
274
275 /*
276  *      Add or replace a pair at the end of a VALUE_PAIR list.
277  */
278 void pairreplace(VALUE_PAIR **first, VALUE_PAIR *replace)
279 {
280         VALUE_PAIR *i, *next;
281         VALUE_PAIR **prev = first;
282
283         if (*first == NULL) {
284                 *first = replace;
285                 return;
286         }
287
288         /*
289          *      Not an empty list, so find item if it is there, and
290          *      replace it. Note, we always replace the first one, and
291          *      we ignore any others that might exist.
292          */
293         for(i = *first; i; i = next) {
294                 next = i->next;
295
296                 /*
297                  *      Found the first attribute, replace it,
298                  *      and return.
299                  */
300                 if ((i->attribute == replace->attribute) &&
301                     (i->vendor == replace->vendor)) {
302                         *prev = replace;
303
304                         /*
305                          *      Should really assert that replace->next == NULL
306                          */
307                         replace->next = next;
308                         pairbasicfree(i);
309                         return;
310                 }
311
312                 /*
313                  *      Point to where the attribute should go.
314                  */
315                 prev = &i->next;
316         }
317
318         /*
319          *      If we got here, we didn't find anything to replace, so
320          *      stopped at the last item, which we just append to.
321          */
322         *prev = replace;
323 }
324
325
326 /*
327  *      Copy just one VP.
328  */
329 VALUE_PAIR *paircopyvp(const VALUE_PAIR *vp)
330 {
331         size_t name_len;
332         VALUE_PAIR *n;
333         
334         if (!vp->flags.unknown_attr) {
335                 name_len = 0;
336         } else {
337                 name_len = FR_VP_NAME_PAD;
338         }
339         
340         if ((n = malloc(sizeof(*n) + name_len)) == NULL) {
341                 fr_strerror_printf("out of memory");
342                 return NULL;
343         }
344         memcpy(n, vp, sizeof(*n) + name_len);
345
346         /*
347          *      Reset the name field to point to the NEW attribute,
348          *      rather than to the OLD one.
349          */
350         if (vp->flags.unknown_attr) n->name = (char *) (n + 1);
351
352         n->next = NULL;
353
354         if ((n->type == PW_TYPE_TLV) &&
355             (n->vp_tlv != NULL)) {
356                 n->vp_tlv = malloc(n->length);
357                 memcpy(n->vp_tlv, vp->vp_tlv, n->length);
358         }
359
360         return n;
361 }
362
363
364 /*
365  *      Copy just a certain type of pairs.
366  */
367 VALUE_PAIR *paircopy2(VALUE_PAIR *vp, unsigned int attr, unsigned int vendor)
368 {
369         VALUE_PAIR      *first, *n, **last;
370
371         first = NULL;
372         last = &first;
373
374         while (vp) {
375                 if ((attr > 0) &&
376                     !((vp->attribute == attr) && (vp->vendor == vendor))) {
377                         vp = vp->next;
378                         continue;
379                 }
380
381                 n = paircopyvp(vp);
382                 if (!n) return first;
383                 *last = n;
384                 last = &n->next;
385                 vp = vp->next;
386         }
387         return first;
388 }
389
390
391 /*
392  *      Copy a pairlist.
393  */
394 VALUE_PAIR *paircopy(VALUE_PAIR *vp)
395 {
396         return paircopy2(vp, 0, 0);
397 }
398
399
400 /*
401  *      Move attributes from one list to the other
402  *      if not already present.
403  */
404 void pairmove(VALUE_PAIR **to, VALUE_PAIR **from)
405 {
406         VALUE_PAIR **tailto, *i, *j, *next;
407         VALUE_PAIR *tailfrom = NULL;
408         VALUE_PAIR *found;
409         int has_password = 0;
410
411         /*
412          *      First, see if there are any passwords here, and
413          *      point "tailto" to the end of the "to" list.
414          */
415         tailto = to;
416         for(i = *to; i; i = i->next) {
417                 if (i->attribute == PW_USER_PASSWORD ||
418                     i->attribute == PW_CRYPT_PASSWORD)
419                         has_password = 1;
420                 tailto = &i->next;
421         }
422
423         /*
424          *      Loop over the "from" list.
425          */
426         for(i = *from; i; i = next) {
427                 next = i->next;
428
429                 /*
430                  *      If there was a password in the "to" list,
431                  *      do not move any other password from the
432                  *      "from" to the "to" list.
433                  */
434                 if (has_password &&
435                     (i->attribute == PW_USER_PASSWORD ||
436                      i->attribute == PW_CRYPT_PASSWORD)) {
437                         tailfrom = i;
438                         continue;
439                 }
440
441                 switch (i->operator) {
442                         /*
443                          *      These are COMPARISON attributes
444                          *      from a check list, and are not
445                          *      supposed to be copied!
446                          */
447                         case T_OP_NE:
448                         case T_OP_GE:
449                         case T_OP_GT:
450                         case T_OP_LE:
451                         case T_OP_LT:
452                         case T_OP_CMP_TRUE:
453                         case T_OP_CMP_FALSE:
454                         case T_OP_CMP_EQ:
455                                 tailfrom = i;
456                                 continue;
457
458                         default:
459                                 break;
460                 }
461
462                 /*
463                  *      If the attribute is already present in "to",
464                  *      do not move it from "from" to "to". We make
465                  *      an exception for "Hint" which can appear multiple
466                  *      times, and we never move "Fall-Through".
467                  */
468                 if (i->attribute == PW_FALL_THROUGH ||
469                     (i->attribute != PW_HINT && i->attribute != PW_FRAMED_ROUTE)) {
470
471                         found = pairfind(*to, i->attribute, i->vendor);
472                         switch (i->operator) {
473
474                           /*
475                            *    If matching attributes are found,
476                            *    delete them.
477                            */
478                         case T_OP_SUB:          /* -= */
479                                 if (found) {
480                                         if (!i->vp_strvalue[0] ||
481                                             (strcmp((char *)found->vp_strvalue,
482                                                     (char *)i->vp_strvalue) == 0)){
483                                                 pairdelete(to, found->attribute, found->vendor);
484
485                                                 /*
486                                                  *      'tailto' may have been
487                                                  *      deleted...
488                                                  */
489                                                 tailto = to;
490                                                 for(j = *to; j; j = j->next) {
491                                                         tailto = &j->next;
492                                                 }
493                                         }
494                                 }
495                                 tailfrom = i;
496                                 continue;
497                                 break;
498
499 /* really HAVE_REGEX_H */
500 #if 0
501                                 /*
502                                  *  Attr-Name =~ "s/find/replace/"
503                                  *
504                                  *  Very bad code.  Barely working,
505                                  *  if at all.
506                                  */
507
508                         case T_OP_REG_EQ:
509                           if (found &&
510                               (i->vp_strvalue[0] == 's')) {
511                             regex_t             reg;
512                             regmatch_t          match[1];
513
514                             char *str;
515                             char *p, *q;
516
517                             p = i->vp_strvalue + 1;
518                             q = strchr(p + 1, *p);
519                             if (!q || (q[strlen(q) - 1] != *p)) {
520                               tailfrom = i;
521                               continue;
522                             }
523                             str = strdup(i->vp_strvalue + 2);
524                             q = strchr(str, *p);
525                             *(q++) = '\0';
526                             q[strlen(q) - 1] = '\0';
527
528                             regcomp(&reg, str, 0);
529                             if (regexec(&reg, found->vp_strvalue,
530                                         1, match, 0) == 0) {
531                               fprintf(stderr, "\"%s\" will have %d to %d replaced with %s\n",
532                                       found->vp_strvalue, match[0].rm_so,
533                                       match[0].rm_eo, q);
534
535                             }
536                             regfree(&reg);
537                             free(str);
538                           }
539                           tailfrom = i; /* don't copy it over */
540                           continue;
541                           break;
542 #endif
543                         case T_OP_EQ:           /* = */
544                                 /*
545                                  *  FIXME: Tunnel attributes with
546                                  *  different tags are different
547                                  *  attributes.
548                                  */
549                                 if (found) {
550                                         tailfrom = i;
551                                         continue; /* with the loop */
552                                 }
553                                 break;
554
555                           /*
556                            *  If a similar attribute is found,
557                            *  replace it with the new one.  Otherwise,
558                            *  add the new one to the list.
559                            */
560                         case T_OP_SET:          /* := */
561                                 if (found) {
562                                         VALUE_PAIR *mynext = found->next;
563
564                                         /*
565                                          *      Do NOT call pairdelete()
566                                          *      here, due to issues with
567                                          *      re-writing "request->username".
568                                          *
569                                          *      Everybody calls pairmove,
570                                          *      and expects it to work.
571                                          *      We can't update request->username
572                                          *      here, so instead we over-write
573                                          *      the vp that it's pointing to.
574                                          */
575                                         memcpy(found, i, sizeof(*found));
576                                         found->next = mynext;
577
578                                         pairdelete(&found->next, found->attribute, found->vendor);
579
580                                         /*
581                                          *      'tailto' may have been
582                                          *      deleted...
583                                          */
584                                         for(j = found; j; j = j->next) {
585                                                 tailto = &j->next;
586                                         }
587                                         continue;
588                                 }
589                                 break;
590
591                           /*
592                            *  Add the new element to the list, even
593                            *  if similar ones already exist.
594                            */
595                         default:
596                         case T_OP_ADD: /* += */
597                                 break;
598                         }
599                 }
600                 if (tailfrom)
601                         tailfrom->next = next;
602                 else
603                         *from = next;
604
605                 /*
606                  *      If ALL of the 'to' attributes have been deleted,
607                  *      then ensure that the 'tail' is updated to point
608                  *      to the head.
609                  */
610                 if (!*to) {
611                         tailto = to;
612                 }
613                 *tailto = i;
614                 if (i) {
615                         i->next = NULL;
616                         tailto = &i->next;
617                 }
618         }
619 }
620
621 /*
622  *      Move one kind of attributes from one list to the other
623  */
624 void pairmove2(VALUE_PAIR **to, VALUE_PAIR **from, unsigned int attr, unsigned int vendor)
625 {
626         VALUE_PAIR *to_tail, *i, *next;
627         VALUE_PAIR *iprev = NULL;
628
629         /*
630          *      Find the last pair in the "to" list and put it in "to_tail".
631          */
632         if (*to != NULL) {
633                 to_tail = *to;
634                 for(i = *to; i; i = i->next)
635                         to_tail = i;
636         } else
637                 to_tail = NULL;
638
639         for(i = *from; i; i = next) {
640                 next = i->next;
641
642                 /*
643                  *      vendor=0, attr = PW_VENDOR_SPECIFIC means
644                  *      "match any vendor attribute".
645                  */
646                 if ((vendor == 0) && (attr == PW_VENDOR_SPECIFIC)) {
647                         /*
648                          *      It's a VSA: move it over.
649                          */
650                         if (i->vendor != 0) goto move;
651
652                         /*
653                          *      It's Vendor-Specific: move it over.
654                          */
655                         if (i->attribute == attr) goto move;
656
657                         /*
658                          *      It's not a VSA: ignore it.
659                          */
660                         iprev = i;
661                         continue;
662                 }
663
664                 /*
665                  *      If it isn't an exact match, ignore it.
666                  */
667                 if (!((i->vendor == vendor) && (i->attribute == attr))) {
668                         iprev = i;
669                         continue;
670                 }
671
672         move:
673                 /*
674                  *      Remove the attribute from the "from" list.
675                  */
676                 if (iprev)
677                         iprev->next = next;
678                 else
679                         *from = next;
680
681                 /*
682                  *      Add the attribute to the "to" list.
683                  */
684                 if (to_tail)
685                         to_tail->next = i;
686                 else
687                         *to = i;
688                 to_tail = i;
689                 i->next = NULL;
690         }
691 }
692
693
694 /*
695  *      Sort of strtok/strsep function.
696  */
697 static char *mystrtok(char **ptr, const char *sep)
698 {
699         char    *res;
700
701         if (**ptr == 0)
702                 return NULL;
703         while (**ptr && strchr(sep, **ptr))
704                 (*ptr)++;
705         if (**ptr == 0)
706                 return NULL;
707         res = *ptr;
708         while (**ptr && strchr(sep, **ptr) == NULL)
709                 (*ptr)++;
710         if (**ptr != 0)
711                 *(*ptr)++ = 0;
712         return res;
713 }
714
715 /*
716  *      Turn printable string into time_t
717  *      Returns -1 on error, 0 on OK.
718  */
719 static int gettime(const char *valstr, time_t *date)
720 {
721         int             i;
722         time_t          t;
723         struct tm       *tm, s_tm;
724         char            buf[64];
725         char            *p;
726         char            *f[4];
727         char            *tail = '\0';
728
729         /*
730          * Test for unix timestamp date
731          */
732         *date = strtoul(valstr, &tail, 10);
733         if (*tail == '\0') {
734                 return 0;
735         }
736
737         tm = &s_tm;
738         memset(tm, 0, sizeof(*tm));
739         tm->tm_isdst = -1;      /* don't know, and don't care about DST */
740
741         strlcpy(buf, valstr, sizeof(buf));
742
743         p = buf;
744         f[0] = mystrtok(&p, " \t");
745         f[1] = mystrtok(&p, " \t");
746         f[2] = mystrtok(&p, " \t");
747         f[3] = mystrtok(&p, " \t"); /* may, or may not, be present */
748         if (!f[0] || !f[1] || !f[2]) return -1;
749
750         /*
751          *      The time has a colon, where nothing else does.
752          *      So if we find it, bubble it to the back of the list.
753          */
754         if (f[3]) {
755                 for (i = 0; i < 3; i++) {
756                         if (strchr(f[i], ':')) {
757                                 p = f[3];
758                                 f[3] = f[i];
759                                 f[i] = p;
760                                 break;
761                         }
762                 }
763         }
764
765         /*
766          *  The month is text, which allows us to find it easily.
767          */
768         tm->tm_mon = 12;
769         for (i = 0; i < 3; i++) {
770                 if (isalpha( (int) *f[i])) {
771                         /*
772                          *  Bubble the month to the front of the list
773                          */
774                         p = f[0];
775                         f[0] = f[i];
776                         f[i] = p;
777
778                         for (i = 0; i < 12; i++) {
779                                 if (strncasecmp(months[i], f[0], 3) == 0) {
780                                         tm->tm_mon = i;
781                                         break;
782                                 }
783                         }
784                 }
785         }
786
787         /* month not found? */
788         if (tm->tm_mon == 12) return -1;
789
790         /*
791          *  The year may be in f[1], or in f[2]
792          */
793         tm->tm_year = atoi(f[1]);
794         tm->tm_mday = atoi(f[2]);
795
796         if (tm->tm_year >= 1900) {
797                 tm->tm_year -= 1900;
798
799         } else {
800                 /*
801                  *  We can't use 2-digit years any more, they make it
802                  *  impossible to tell what's the day, and what's the year.
803                  */
804                 if (tm->tm_mday < 1900) return -1;
805
806                 /*
807                  *  Swap the year and the day.
808                  */
809                 i = tm->tm_year;
810                 tm->tm_year = tm->tm_mday - 1900;
811                 tm->tm_mday = i;
812         }
813
814         /*
815          *  If the day is out of range, die.
816          */
817         if ((tm->tm_mday < 1) || (tm->tm_mday > 31)) {
818                 return -1;
819         }
820
821         /*
822          *      There may be %H:%M:%S.  Parse it in a hacky way.
823          */
824         if (f[3]) {
825                 f[0] = f[3];    /* HH */
826                 f[1] = strchr(f[0], ':'); /* find : separator */
827                 if (!f[1]) return -1;
828
829                 *(f[1]++) = '\0'; /* nuke it, and point to MM:SS */
830
831                 f[2] = strchr(f[1], ':'); /* find : separator */
832                 if (f[2]) {
833                   *(f[2]++) = '\0';     /* nuke it, and point to SS */
834                   tm->tm_sec = atoi(f[2]);
835                 }                       /* else leave it as zero */
836
837                 tm->tm_hour = atoi(f[0]);
838                 tm->tm_min = atoi(f[1]);
839         }
840
841         /*
842          *  Returns -1 on error.
843          */
844         t = mktime(tm);
845         if (t == (time_t) -1) return -1;
846
847         *date = t;
848
849         return 0;
850 }
851
852 static const char *hextab = "0123456789abcdef";
853
854 /*
855  *  Parse a string value into a given VALUE_PAIR
856  *
857  *  FIXME: we probably want to fix this function to accept
858  *  octets as values for any type of attribute.  We should then
859  *  double-check the parsed value, to be sure it's legal for that
860  *  type (length, etc.)
861  */
862 static uint32_t getint(const char *value, char **end)
863 {
864         if ((value[0] == '0') && (value[1] == 'x')) {
865                 return strtoul(value, end, 16);
866         }
867
868         return strtoul(value, end, 10);
869 }
870
871 static int check_for_whitespace(const char *value)
872 {
873         while (*value) {
874                 if (!isspace((int) *value)) return 0;
875
876                 value++;
877         }
878
879         return 1;
880 }
881
882
883 VALUE_PAIR *pairparsevalue(VALUE_PAIR *vp, const char *value)
884 {
885         char            *p, *s=0;
886         const char      *cp, *cs;
887         int             x;
888         size_t          length;
889         DICT_VALUE      *dval;
890
891         if (!value) return NULL;
892
893         /*
894          *      Even for integers, dates and ip addresses we
895          *      keep the original string in vp->vp_strvalue.
896          */
897         if (vp->type != PW_TYPE_TLV) {
898                 strlcpy(vp->vp_strvalue, value, sizeof(vp->vp_strvalue));
899                 vp->length = strlen(vp->vp_strvalue);
900         }
901
902         switch(vp->type) {
903                 case PW_TYPE_STRING:
904                         /*
905                          *      Do escaping here
906                          */
907                         p = vp->vp_strvalue;
908                         cp = value;
909                         length = 0;
910
911                         while (*cp && (length < (sizeof(vp->vp_strvalue) - 1))) {
912                                 char c = *cp++;
913
914                                 if (c == '\\') {
915                                         switch (*cp) {
916                                         case 'r':
917                                                 c = '\r';
918                                                 cp++;
919                                                 break;
920                                         case 'n':
921                                                 c = '\n';
922                                                 cp++;
923                                                 break;
924                                         case 't':
925                                                 c = '\t';
926                                                 cp++;
927                                                 break;
928                                         case '"':
929                                                 c = '"';
930                                                 cp++;
931                                                 break;
932                                         case '\'':
933                                                 c = '\'';
934                                                 cp++;
935                                                 break;
936                                         case '\\':
937                                                 c = '\\';
938                                                 cp++;
939                                                 break;
940                                         case '`':
941                                                 c = '`';
942                                                 cp++;
943                                                 break;
944                                         case '\0':
945                                                 c = '\\'; /* no cp++ */
946                                                 break;
947                                         default:
948                                                 if ((cp[0] >= '0') &&
949                                                     (cp[0] <= '9') &&
950                                                     (cp[1] >= '0') &&
951                                                     (cp[1] <= '9') &&
952                                                     (cp[2] >= '0') &&
953                                                     (cp[2] <= '9') &&
954                                                     (sscanf(cp, "%3o", &x) == 1)) {
955                                                         c = x;
956                                                         cp += 3;
957                                                 } /* else just do '\\' */
958                                         }
959                                 }
960                                 *p++ = c;
961                                 length++;
962                         }
963                         vp->vp_strvalue[length] = '\0';
964                         vp->length = length;
965                         break;
966
967                 case PW_TYPE_IPADDR:
968                         /*
969                          *      It's a comparison, not a real IP.
970                          */
971                         if ((vp->operator == T_OP_REG_EQ) ||
972                             (vp->operator == T_OP_REG_NE)) {
973                                 break;
974                         }
975
976                         /*
977                          *      FIXME: complain if hostname
978                          *      cannot be resolved, or resolve later!
979                          */
980                         s = NULL;
981                         if ((p = strrchr(value, '+')) != NULL && !p[1]) {
982                                 cs = s = strdup(value);
983                                 if (!s) return NULL;
984                                 p = strrchr(s, '+');
985                                 *p = 0;
986                                 vp->flags.addport = 1;
987                         } else {
988                                 p = NULL;
989                                 cs = value;
990                         }
991
992                         {
993                                 fr_ipaddr_t ipaddr;
994
995                                 if (ip_hton(cs, AF_INET, &ipaddr) < 0) {
996                                         free(s);
997                                         fr_strerror_printf("Failed to find IP address for %s", cs);
998                                         return NULL;
999                                 }
1000
1001                                 vp->vp_ipaddr = ipaddr.ipaddr.ip4addr.s_addr;
1002                         }
1003                         free(s);
1004                         vp->length = 4;
1005                         break;
1006
1007                 case PW_TYPE_BYTE:
1008                         vp->length = 1;
1009
1010                         /*
1011                          *      Note that ALL integers are unsigned!
1012                          */
1013                         vp->vp_integer = getint(value, &p);
1014                         if (!*p) {
1015                                 if (vp->vp_integer > 255) {
1016                                         fr_strerror_printf("Byte value \"%s\" is larger than 255", value);
1017                                         return NULL;
1018                                 }
1019                                 break;
1020                         }
1021                         if (check_for_whitespace(p)) break;
1022                         goto check_for_value;
1023
1024                 case PW_TYPE_SHORT:
1025                         /*
1026                          *      Note that ALL integers are unsigned!
1027                          */
1028                         vp->vp_integer = getint(value, &p);
1029                         vp->length = 2;
1030                         if (!*p) {
1031                                 if (vp->vp_integer > 65535) {
1032                                         fr_strerror_printf("Byte value \"%s\" is larger than 65535", value);
1033                                         return NULL;
1034                                 }
1035                                 break;
1036                         }
1037                         if (check_for_whitespace(p)) break;
1038                         goto check_for_value;
1039
1040                 case PW_TYPE_INTEGER:
1041                         /*
1042                          *      Note that ALL integers are unsigned!
1043                          */
1044                         vp->vp_integer = getint(value, &p);
1045                         vp->length = 4;
1046                         if (!*p) break;
1047                         if (check_for_whitespace(p)) break;
1048
1049         check_for_value:
1050                         /*
1051                          *      Look for the named value for the given
1052                          *      attribute.
1053                          */
1054                         if ((dval = dict_valbyname(vp->attribute, vp->vendor, value)) == NULL) {
1055                                 fr_strerror_printf("Unknown value %s for attribute %s",
1056                                            value, vp->name);
1057                                 return NULL;
1058                         }
1059                         vp->vp_integer = dval->value;
1060                         break;
1061
1062                 case PW_TYPE_DATE:
1063                         {
1064                                 /*
1065                                  *      time_t may be 64 bits, whule vp_date
1066                                  *      MUST be 32-bits.  We need an
1067                                  *      intermediary variable to handle
1068                                  *      the conversions.
1069                                  */
1070                                 time_t date;
1071
1072                                 if (gettime(value, &date) < 0) {
1073                                         fr_strerror_printf("failed to parse time string "
1074                                                    "\"%s\"", value);
1075                                         return NULL;
1076                                 }
1077
1078                                 vp->vp_date = date;
1079                         }
1080                         vp->length = 4;
1081                         break;
1082
1083                 case PW_TYPE_ABINARY:
1084 #ifdef ASCEND_BINARY
1085                         if (strncasecmp(value, "0x", 2) == 0) {
1086                                 vp->type = PW_TYPE_OCTETS;
1087                                 goto do_octets;
1088                         }
1089
1090                         if (ascend_parse_filter(vp) < 0 ) {
1091                                 fr_strerror_printf("failed to parse Ascend binary attribute: %s",
1092                                            fr_strerror());
1093                                 return NULL;
1094                         }
1095                         break;
1096
1097                         /*
1098                          *      If Ascend binary is NOT defined,
1099                          *      then fall through to raw octets, so that
1100                          *      the user can at least make them by hand...
1101                          */
1102         do_octets:
1103 #endif
1104                         /* raw octets: 0x01020304... */
1105                 case PW_TYPE_OCTETS:
1106                         if (strncasecmp(value, "0x", 2) == 0) {
1107                                 uint8_t *us;
1108                                 cp = value + 2;
1109                                 us = vp->vp_octets;
1110                                 vp->length = 0;
1111
1112
1113                                 /*
1114                                  *      There is only one character,
1115                                  *      die.
1116                                  */
1117                                 if ((strlen(cp) & 0x01) != 0) {
1118                                         fr_strerror_printf("Hex string is not an even length string.");
1119                                         return NULL;
1120                                 }
1121
1122
1123                                 while (*cp &&
1124                                        (vp->length < MAX_STRING_LEN)) {
1125                                         unsigned int tmp;
1126
1127                                         if (sscanf(cp, "%02x", &tmp) != 1) {
1128                                                 fr_strerror_printf("Non-hex characters at %c%c", cp[0], cp[1]);
1129                                                 return NULL;
1130                                         }
1131
1132                                         cp += 2;
1133                                         *(us++) = tmp;
1134                                         vp->length++;
1135                                 }
1136                         }
1137                         break;
1138
1139                 case PW_TYPE_IFID:
1140                         if (ifid_aton(value, (void *) &vp->vp_ifid) == NULL) {
1141                                 fr_strerror_printf("failed to parse interface-id "
1142                                            "string \"%s\"", value);
1143                                 return NULL;
1144                         }
1145                         vp->length = 8;
1146                         break;
1147
1148                 case PW_TYPE_IPV6ADDR:
1149                         {
1150                                 fr_ipaddr_t ipaddr;
1151
1152                                 if (ip_hton(value, AF_INET6, &ipaddr) < 0) {
1153                                         char buffer[1024];
1154
1155                                         strlcpy(buffer, fr_strerror(), sizeof(buffer));
1156
1157                                         fr_strerror_printf("failed to parse IPv6 address "
1158                                                            "string \"%s\": %s", value, buffer);
1159                                         return NULL;
1160                                 }
1161                                 vp->vp_ipv6addr = ipaddr.ipaddr.ip6addr;
1162                                 vp->length = 16; /* length of IPv6 address */
1163                         }
1164                         break;
1165
1166                 case PW_TYPE_IPV6PREFIX:
1167                         p = strchr(value, '/');
1168                         if (!p || ((p - value) >= 256)) {
1169                                 fr_strerror_printf("invalid IPv6 prefix "
1170                                            "string \"%s\"", value);
1171                                 return NULL;
1172                         } else {
1173                                 unsigned int prefix;
1174                                 char buffer[256], *eptr;
1175
1176                                 memcpy(buffer, value, p - value);
1177                                 buffer[p - value] = '\0';
1178
1179                                 if (inet_pton(AF_INET6, buffer, vp->vp_octets + 2) <= 0) {
1180                                         fr_strerror_printf("failed to parse IPv6 address "
1181                                                    "string \"%s\"", value);
1182                                         return NULL;
1183                                 }
1184
1185                                 prefix = strtoul(p + 1, &eptr, 10);
1186                                 if ((prefix > 128) || *eptr) {
1187                                         fr_strerror_printf("failed to parse IPv6 address "
1188                                                    "string \"%s\"", value);
1189                                         return NULL;
1190                                 }
1191                                 vp->vp_octets[1] = prefix;
1192                         }
1193                         vp->vp_octets[0] = '\0';
1194                         vp->length = 16 + 2;
1195                         break;
1196
1197                 case PW_TYPE_ETHERNET:
1198                         {
1199                                 const char *c1, *c2;
1200
1201                                 length = 0;
1202                                 cp = value;
1203                                 while (*cp) {
1204                                         if (cp[1] == ':') {
1205                                                 c1 = hextab;
1206                                                 c2 = memchr(hextab, tolower((int) cp[0]), 16);
1207                                                 cp += 2;
1208                                         } else if ((cp[1] != '\0') &&
1209                                                    ((cp[2] == ':') ||
1210                                                     (cp[2] == '\0'))) {
1211                                                    c1 = memchr(hextab, tolower((int) cp[0]), 16);
1212                                                    c2 = memchr(hextab, tolower((int) cp[1]), 16);
1213                                                    cp += 2;
1214                                                    if (*cp == ':') cp++;
1215                                         } else {
1216                                                 c1 = c2 = NULL;
1217                                         }
1218                                         if (!c1 || !c2 || (length >= sizeof(vp->vp_ether))) {
1219                                                 fr_strerror_printf("failed to parse Ethernet address \"%s\"", value);
1220                                                 return NULL;
1221                                         }
1222                                         vp->vp_ether[length] = ((c1-hextab)<<4) + (c2-hextab);
1223                                         length++;
1224                                 }
1225                         }
1226                         vp->length = 6;
1227                         break;
1228
1229                 case PW_TYPE_COMBO_IP:
1230                         if (inet_pton(AF_INET6, value, vp->vp_strvalue) > 0) {
1231                                 vp->type = PW_TYPE_IPV6ADDR;
1232                                 vp->length = 16; /* length of IPv6 address */
1233                                 vp->vp_strvalue[vp->length] = '\0';
1234
1235                         } else {
1236                                 fr_ipaddr_t ipaddr;
1237
1238                                 if (ip_hton(value, AF_INET, &ipaddr) < 0) {
1239                                         fr_strerror_printf("Failed to find IPv4 address for %s", value);
1240                                         return NULL;
1241                                 }
1242
1243                                 vp->type = PW_TYPE_IPADDR;
1244                                 vp->vp_ipaddr = ipaddr.ipaddr.ip4addr.s_addr;
1245                                 vp->length = 4;
1246                         }
1247                         break;
1248
1249                 case PW_TYPE_SIGNED: /* Damned code for 1 WiMAX attribute */
1250                         vp->vp_signed = (int32_t) strtol(value, &p, 10);
1251                         vp->length = 4;
1252                         break;
1253
1254                 case PW_TYPE_TLV: /* don't use this! */
1255                         if (strncasecmp(value, "0x", 2) != 0) {
1256                                 fr_strerror_printf("Invalid TLV specification");
1257                                 return NULL;
1258                         }
1259                         length = strlen(value + 2) / 2;
1260                         if (vp->length < length) {
1261                                 free(vp->vp_tlv);
1262                                 vp->vp_tlv = NULL;
1263                         }
1264                         vp->vp_tlv = malloc(length);
1265                         if (!vp->vp_tlv) {
1266                                 fr_strerror_printf("No memory");
1267                                 return NULL;
1268                         }
1269                         if (fr_hex2bin(value + 2, vp->vp_tlv,
1270                                        length) != length) {
1271                                 fr_strerror_printf("Invalid hex data in TLV");
1272                                 return NULL;
1273                         }
1274                         vp->length = length;
1275                         break;
1276
1277                         /*
1278                          *  Anything else.
1279                          */
1280                 default:
1281                         fr_strerror_printf("unknown attribute type %d", vp->type);
1282                         return NULL;
1283         }
1284
1285         return vp;
1286 }
1287
1288 /*
1289  *      Create a VALUE_PAIR from an ASCII attribute and value,
1290  *      where the attribute name is in the form:
1291  *
1292  *      Attr-%d
1293  *      Vendor-%d-Attr-%d
1294  *      VendorName-Attr-%d
1295  */
1296 static VALUE_PAIR *pairmake_any(const char *attribute, const char *value,
1297                                 int operator)
1298 {
1299         int             attr, vendor;
1300         size_t          size;
1301         const char      *p = attribute;
1302         char            *q;
1303         VALUE_PAIR      *vp;
1304
1305         /*
1306          *      Unknown attributes MUST be of type 'octets'
1307          */
1308         if (value && (strncasecmp(value, "0x", 2) != 0)) {
1309                 fr_strerror_printf("Invalid octet string \"%s\" for attribute name \"%s\"", value, attribute);
1310                 return NULL;
1311         }
1312
1313         vendor = 0;
1314
1315         /*
1316          *      Pull off vendor prefix first.
1317          */
1318         if (strncasecmp(p, "Attr-", 5) != 0) {
1319                 if (strncasecmp(p, "Vendor-", 7) == 0) {
1320                         vendor = (int) strtol(p + 7, &q, 10);
1321                         if ((vendor == 0) || (vendor > FR_MAX_VENDOR)) {
1322                                 fr_strerror_printf("Invalid vendor value in attribute name \"%s\"", attribute);
1323                                 return NULL;
1324                         }
1325
1326                         p = q;
1327
1328                 } else {        /* must be vendor name */
1329                         char buffer[256];
1330
1331                         q = strchr(p, '-');
1332
1333                         if (!q) {
1334                                 fr_strerror_printf("Invalid vendor name in attribute name \"%s\"", attribute);
1335                                 return NULL;
1336                         }
1337
1338                         if ((size_t) (q - p) >= sizeof(buffer)) {
1339                                 fr_strerror_printf("Vendor name too long in attribute name \"%s\"", attribute);
1340                                 return NULL;
1341                         }
1342
1343                         memcpy(buffer, p, (q - p));
1344                         buffer[q - p] = '\0';
1345
1346                         vendor = dict_vendorbyname(buffer);
1347                         if (!vendor) {
1348                                 fr_strerror_printf("Unknown vendor name in attribute name \"%s\"", attribute);
1349                                 return NULL;
1350                         }
1351
1352                         p = q;
1353                 }
1354
1355                 if (*p != '-') {
1356                         fr_strerror_printf("Invalid text following vendor definition in attribute name \"%s\"", attribute);
1357                         return NULL;
1358                 }
1359                 p++;
1360         }
1361
1362         /*
1363          *      Attr-%d
1364          */
1365         if (strncasecmp(p, "Attr-", 5) != 0) {
1366                 fr_strerror_printf("Invalid format in attribute name \"%s\"", attribute);
1367                 return NULL;
1368         }
1369
1370         attr = strtol(p + 5, &q, 10);
1371
1372         /*
1373          *      Invalid, or trailing text after number.
1374          */
1375         if ((attr == 0) || *q) {
1376                 fr_strerror_printf("Invalid value in attribute name \"%s\"", attribute);
1377                 return NULL;
1378         }
1379
1380         /*
1381          *      Double-check the size of attr.
1382          */
1383         if (vendor) {
1384                 DICT_VENDOR *dv = dict_vendorbyvalue(vendor);
1385
1386                 if (!dv) {
1387                         if (attr > 255) {
1388                         attr_error:
1389                                 fr_strerror_printf("Invalid attribute number in attribute name \"%s\"", attribute);
1390                                 return NULL;
1391                         }
1392
1393                 } else switch (dv->type) {
1394                         case 1:
1395                                 if (attr > 255) goto attr_error;
1396                                 break;
1397
1398                         case 2:
1399                                 if (attr > 65535) goto attr_error;
1400                                 break;
1401
1402                         case 4:
1403                                 break;
1404
1405                         default:
1406                                 fr_strerror_printf("Internal sanity check failed");
1407                                 return NULL;
1408                 }
1409         }
1410
1411         /*
1412          *      We've now parsed the attribute properly, Let's create
1413          *      it.  This next stop also looks the attribute up in the
1414          *      dictionary, and creates the appropriate type for it.
1415          */
1416         if ((vp = paircreate(attr, vendor, PW_TYPE_OCTETS)) == NULL) {
1417                 fr_strerror_printf("out of memory");
1418                 return NULL;
1419         }
1420
1421         vp->operator = (operator == 0) ? T_OP_EQ : operator;
1422         if (!value) return vp;
1423
1424         size = strlen(value + 2);
1425
1426         /*
1427          *      We may be reading something like Attr-5.  i.e.
1428          *      who-ever wrote the text didn't understand it, but we
1429          *      do.
1430          */
1431         switch (vp->type) {
1432         default:
1433                 if (size == (vp->length * 2)) break;
1434                 vp->type = PW_TYPE_OCTETS;
1435                 /* FALL-THROUGH */
1436                 
1437         case PW_TYPE_STRING:
1438         case PW_TYPE_OCTETS:
1439         case PW_TYPE_ABINARY:
1440                 vp->length = size >> 1;
1441                 break;
1442         }
1443
1444         if (fr_hex2bin(value + 2, vp->vp_octets, size) != vp->length) {
1445                 fr_strerror_printf("Invalid hex string");
1446                 free(vp);
1447                 return NULL;
1448         }
1449
1450         /*
1451          *      Move contents around based on type.  This is
1452          *      to work around the historical use of "lvalue".
1453          */
1454         switch (vp->type) {
1455         case PW_TYPE_DATE:
1456         case PW_TYPE_IPADDR:
1457         case PW_TYPE_INTEGER:
1458                 memcpy(&vp->lvalue, vp->vp_octets, sizeof(vp->lvalue));
1459                 vp->vp_strvalue[0] = '\0';
1460                 break;
1461                 
1462         default:
1463                 break;
1464         }
1465        
1466         return vp;
1467 }
1468
1469
1470 /*
1471  *      Create a VALUE_PAIR from an ASCII attribute and value.
1472  */
1473 VALUE_PAIR *pairmake(const char *attribute, const char *value, int operator)
1474 {
1475         DICT_ATTR       *da;
1476         VALUE_PAIR      *vp;
1477         char            *tc, *ts;
1478         signed char     tag;
1479         int             found_tag;
1480         char            buffer[64];
1481         const char      *attrname = attribute;
1482
1483         /*
1484          *    Check for tags in 'Attribute:Tag' format.
1485          */
1486         found_tag = 0;
1487         tag = 0;
1488
1489         ts = strrchr(attribute, ':');
1490         if (ts && !ts[1]) {
1491                 fr_strerror_printf("Invalid tag for attribute %s", attribute);
1492                 return NULL;
1493         }
1494
1495         if (ts && ts[1]) {
1496                 strlcpy(buffer, attribute, sizeof(buffer));
1497                 attrname = buffer;
1498                 ts = strrchr(attrname, ':');
1499
1500                  /* Colon found with something behind it */
1501                  if (ts[1] == '*' && ts[2] == 0) {
1502                          /* Wildcard tag for check items */
1503                          tag = TAG_ANY;
1504                          *ts = 0;
1505                  } else if ((ts[1] >= '0') && (ts[1] <= '9')) {
1506                          /* It's not a wild card tag */
1507                          tag = strtol(ts + 1, &tc, 0);
1508                          if (tc && !*tc && TAG_VALID_ZERO(tag))
1509                                  *ts = 0;
1510                          else tag = 0;
1511                  } else {
1512                          fr_strerror_printf("Invalid tag for attribute %s", attribute);
1513                          return NULL;
1514                  }
1515                  found_tag = 1;
1516         }
1517
1518         /*
1519          *      It's not found in the dictionary, so we use
1520          *      another method to create the attribute.
1521          */
1522         if ((da = dict_attrbyname(attrname)) == NULL) {
1523                 return pairmake_any(attrname, value, operator);
1524         }
1525
1526         if ((vp = pairalloc(da)) == NULL) {
1527                 fr_strerror_printf("out of memory");
1528                 return NULL;
1529         }
1530         vp->operator = (operator == 0) ? T_OP_EQ : operator;
1531
1532         /*      Check for a tag in the 'Merit' format of:
1533          *      :Tag:Value.  Print an error if we already found
1534          *      a tag in the Attribute.
1535          */
1536
1537         if (value && (*value == ':' && da->flags.has_tag)) {
1538                 /* If we already found a tag, this is invalid */
1539                 if(found_tag) {
1540                         fr_strerror_printf("Duplicate tag %s for attribute %s",
1541                                    value, vp->name);
1542                         DEBUG("Duplicate tag %s for attribute %s\n",
1543                                    value, vp->name);
1544                         pairbasicfree(vp);
1545                         return NULL;
1546                 }
1547                 /* Colon found and attribute allows a tag */
1548                 if (value[1] == '*' && value[2] == ':') {
1549                        /* Wildcard tag for check items */
1550                        tag = TAG_ANY;
1551                        value += 3;
1552                 } else {
1553                        /* Real tag */
1554                        tag = strtol(value + 1, &tc, 0);
1555                        if (tc && *tc==':' && TAG_VALID_ZERO(tag))
1556                             value = tc + 1;
1557                        else tag = 0;
1558                 }
1559                 found_tag = 1;
1560         }
1561
1562         if (found_tag) {
1563           vp->flags.tag = tag;
1564         }
1565
1566         switch (vp->operator) {
1567         default:
1568                 break;
1569
1570                 /*
1571                  *      For =* and !* operators, the value is irrelevant
1572                  *      so we return now.
1573                  */
1574         case T_OP_CMP_TRUE:
1575         case T_OP_CMP_FALSE:
1576                 vp->vp_strvalue[0] = '\0';
1577                 vp->length = 0;
1578                 return vp;
1579                 break;
1580
1581                 /*
1582                  *      Regular expression comparison of integer attributes
1583                  *      does a STRING comparison of the names of their
1584                  *      integer attributes.
1585                  */
1586         case T_OP_REG_EQ:       /* =~ */
1587         case T_OP_REG_NE:       /* !~ */
1588                 if (!value) {
1589                         fr_strerror_printf("No regular expression found in %s",
1590                                            vp->name);
1591                         pairbasicfree(vp);
1592                         return NULL;
1593                 }
1594           
1595                 strlcpy(vp->vp_strvalue, value, sizeof(vp->vp_strvalue));
1596                 vp->length = strlen(vp->vp_strvalue);
1597                 /*
1598                  *      If anything goes wrong, this is a run-time error,
1599                  *      not a compile-time error.
1600                  */
1601                 return vp;
1602
1603         }
1604
1605         /*
1606          *      FIXME: if (strcasecmp(attribute, vp->name) != 0)
1607          *      then the user MAY have typed in the attribute name
1608          *      as Vendor-%d-Attr-%d, and the value MAY be octets.
1609          *
1610          *      We probably want to fix pairparsevalue to accept
1611          *      octets as values for any attribute.
1612          */
1613         if (value && (pairparsevalue(vp, value) == NULL)) {
1614                 pairbasicfree(vp);
1615                 return NULL;
1616         }
1617
1618         return vp;
1619 }
1620
1621
1622 /*
1623  *      [a-zA-Z0-9_-:]+
1624  */
1625 static const int valid_attr_name[256] = {
1626         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1627         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1628         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
1629         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
1630         0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1631         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
1632         0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1633         1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
1634         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1635         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1636         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1637         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1638         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1639         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1640         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1641         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1642 };
1643
1644 /*
1645  *      Read a valuepair from a buffer, and advance pointer.
1646  *      Sets *eol to T_EOL if end of line was encountered.
1647  */
1648 VALUE_PAIR *pairread(const char **ptr, FR_TOKEN *eol)
1649 {
1650         char            buf[64];
1651         char            attr[64];
1652         char            value[1024], *q;
1653         const char      *p;
1654         FR_TOKEN        token, t, xlat;
1655         VALUE_PAIR      *vp;
1656         size_t          len;
1657
1658         *eol = T_OP_INVALID;
1659
1660         p = *ptr;
1661         while ((*p == ' ') || (*p == '\t')) p++;
1662
1663         if (!*p) {
1664                 *eol = T_OP_INVALID;
1665                 fr_strerror_printf("No token read where we expected an attribute name");
1666                 return NULL;
1667         }
1668
1669         if (*p == '#') {
1670                 *eol = T_HASH;
1671                 fr_strerror_printf("Read a comment instead of a token");
1672                 return NULL;
1673         }
1674
1675         q = attr;
1676         for (len = 0; len < sizeof(attr); len++) {
1677                 if (valid_attr_name[(int)*p]) {
1678                         *q++ = *p++;
1679                         continue;
1680                 }
1681                 break;
1682         }
1683
1684         if (len == sizeof(attr)) {
1685                 *eol = T_OP_INVALID;
1686                 fr_strerror_printf("Attribute name is too long");
1687                 return NULL;
1688         }
1689
1690         /*
1691          *      We may have Foo-Bar:= stuff, so back up.
1692          */
1693         if ((len > 0) && (attr[len - 1] == ':')) {
1694                 p--;
1695                 len--;
1696         }
1697
1698         attr[len] = '\0';
1699         *ptr = p;
1700
1701         /* Now we should have an operator here. */
1702         token = gettoken(ptr, buf, sizeof(buf));
1703         if (token < T_EQSTART || token > T_EQEND) {
1704                 fr_strerror_printf("expecting operator");
1705                 return NULL;
1706         }
1707
1708         /* Read value.  Note that empty string values are allowed */
1709         xlat = gettoken(ptr, value, sizeof(value));
1710         if (xlat == T_EOL) {
1711                 fr_strerror_printf("failed to get value");
1712                 return NULL;
1713         }
1714
1715         /*
1716          *      Peek at the next token. Must be T_EOL, T_COMMA, or T_HASH
1717          */
1718         p = *ptr;
1719         t = gettoken(&p, buf, sizeof(buf));
1720         if (t != T_EOL && t != T_COMMA && t != T_HASH) {
1721                 fr_strerror_printf("Expected end of line or comma");
1722                 return NULL;
1723         }
1724
1725         *eol = t;
1726         if (t == T_COMMA) {
1727                 *ptr = p;
1728         }
1729
1730         vp = NULL;
1731         switch (xlat) {
1732                 /*
1733                  *      Make the full pair now.
1734                  */
1735         default:
1736                 vp = pairmake(attr, value, token);
1737                 break;
1738
1739                 /*
1740                  *      Perhaps do xlat's
1741                  */
1742         case T_DOUBLE_QUOTED_STRING:
1743                 p = strchr(value, '%');
1744                 if (p && (p[1] == '{')) {
1745                         if (strlen(value) >= sizeof(vp->vp_strvalue)) {
1746                                 fr_strerror_printf("Value too long");
1747                                 return NULL;
1748                         }
1749                         vp = pairmake(attr, NULL, token);
1750                         if (!vp) {
1751                                 *eol = T_OP_INVALID;
1752                                 return NULL;
1753                         }
1754
1755                         strlcpy(vp->vp_strvalue, value, sizeof(vp->vp_strvalue));
1756                         vp->flags.do_xlat = 1;
1757                         vp->length = 0;
1758                 } else {
1759                         /*
1760                          *      Parse && escape it, as defined by the
1761                          *      data type.
1762                          */
1763                         vp = pairmake(attr, value, token);
1764                         if (!vp) {
1765                                 *eol = T_OP_INVALID;
1766                                 return NULL;
1767                         }
1768                 }
1769                 break;
1770
1771         case T_SINGLE_QUOTED_STRING:
1772                 vp = pairmake(attr, NULL, token);
1773                 if (!vp) {
1774                         *eol = T_OP_INVALID;
1775                         return NULL;
1776                 }
1777
1778                 /*
1779                  *      String and octet types get copied verbatim.
1780                  */
1781                 if ((vp->type == PW_TYPE_STRING) ||
1782                     (vp->type == PW_TYPE_OCTETS)) {
1783                         strlcpy(vp->vp_strvalue, value,
1784                                 sizeof(vp->vp_strvalue));
1785                         vp->length = strlen(vp->vp_strvalue);
1786
1787                         /*
1788                          *      Everything else gets parsed: it's
1789                          *      DATA, not a string!
1790                          */
1791                 } else if (!pairparsevalue(vp, value)) {
1792                         pairfree(&vp);
1793                         *eol = T_OP_INVALID;
1794                         return NULL;
1795                 }
1796                 break;
1797
1798                 /*
1799                  *      Mark the pair to be allocated later.
1800                  */
1801         case T_BACK_QUOTED_STRING:
1802                 if (strlen(value) >= sizeof(vp->vp_strvalue)) {
1803                         fr_strerror_printf("Value too long");
1804                         return NULL;
1805                 }
1806
1807                 vp = pairmake(attr, NULL, token);
1808                 if (!vp) {
1809                         *eol = T_OP_INVALID;
1810                         return NULL;
1811                 }
1812
1813                 vp->flags.do_xlat = 1;
1814                 strlcpy(vp->vp_strvalue, value, sizeof(vp->vp_strvalue));
1815                 vp->length = 0;
1816                 break;
1817         }
1818
1819         /*
1820          *      If we didn't make a pair, return an error.
1821          */
1822         if (!vp) {
1823                 *eol = T_OP_INVALID;
1824                 return NULL;
1825         }
1826
1827         return vp;
1828 }
1829
1830 /*
1831  *      Read one line of attribute/value pairs. This might contain
1832  *      multiple pairs seperated by comma's.
1833  */
1834 FR_TOKEN userparse(const char *buffer, VALUE_PAIR **first_pair)
1835 {
1836         VALUE_PAIR      *vp;
1837         const char      *p;
1838         FR_TOKEN        last_token = T_OP_INVALID;
1839         FR_TOKEN        previous_token;
1840
1841         /*
1842          *      We allow an empty line.
1843          */
1844         if (buffer[0] == 0)
1845                 return T_EOL;
1846
1847         p = buffer;
1848         do {
1849                 previous_token = last_token;
1850                 if ((vp = pairread(&p, &last_token)) == NULL) {
1851                         return last_token;
1852                 }
1853                 pairadd(first_pair, vp);
1854         } while (*p && (last_token == T_COMMA));
1855
1856         /*
1857          *      Don't tell the caller that there was a comment.
1858          */
1859         if (last_token == T_HASH) {
1860                 return previous_token;
1861         }
1862
1863         /*
1864          *      And return the last token which we read.
1865          */
1866         return last_token;
1867 }
1868
1869 /*
1870  *      Read valuepairs from the fp up to End-Of-File.
1871  *
1872  *      Hmm... this function is only used by radclient..
1873  */
1874 VALUE_PAIR *readvp2(FILE *fp, int *pfiledone, const char *errprefix)
1875 {
1876         char buf[8192];
1877         FR_TOKEN last_token = T_EOL;
1878         VALUE_PAIR *vp;
1879         VALUE_PAIR *list;
1880         int error = 0;
1881
1882         list = NULL;
1883
1884         while (!error && fgets(buf, sizeof(buf), fp) != NULL) {
1885                 /*
1886                  *      If we get a '\n' by itself, we assume that's
1887                  *      the end of that VP
1888                  */
1889                 if ((buf[0] == '\n') && (list)) {
1890                         return list;
1891                 }
1892                 if ((buf[0] == '\n') && (!list)) {
1893                         continue;
1894                 }
1895
1896                 /*
1897                  *      Comments get ignored
1898                  */
1899                 if (buf[0] == '#') continue;
1900
1901                 /*
1902                  *      Read all of the attributes on the current line.
1903                  */
1904                 vp = NULL;
1905                 last_token = userparse(buf, &vp);
1906                 if (!vp) {
1907                         if (last_token != T_EOL) {
1908                                 fr_perror("%s", errprefix);
1909                                 error = 1;
1910                                 break;
1911                         }
1912                         break;
1913                 }
1914
1915                 pairadd(&list, vp);
1916                 buf[0] = '\0';
1917         }
1918
1919         if (error) pairfree(&list);
1920
1921         *pfiledone = 1;
1922
1923         return error ? NULL: list;
1924 }
1925
1926
1927
1928 /*
1929  *      Compare two pairs, using the operator from "one".
1930  *
1931  *      i.e. given two attributes, it does:
1932  *
1933  *      (two->data) (one->operator) (one->data)
1934  *
1935  *      e.g. "foo" != "bar"
1936  *
1937  *      Returns true (comparison is true), or false (comparison is not true);
1938  *
1939  *      FIXME: Ignores tags!
1940  */
1941 int paircmp(VALUE_PAIR *one, VALUE_PAIR *two)
1942 {
1943         int compare;
1944
1945         switch (one->operator) {
1946         case T_OP_CMP_TRUE:
1947                 return (two != NULL);
1948
1949         case T_OP_CMP_FALSE:
1950                 return (two == NULL);
1951
1952                 /*
1953                  *      One is a regex, compile it, print two to a string,
1954                  *      and then do string comparisons.
1955                  */
1956         case T_OP_REG_EQ:
1957         case T_OP_REG_NE:
1958 #ifndef HAVE_REGEX_H
1959                 return -1;
1960 #else
1961                 {
1962                         regex_t reg;
1963                         char buffer[MAX_STRING_LEN * 4 + 1];
1964
1965                         compare = regcomp(&reg, one->vp_strvalue,
1966                                           REG_EXTENDED);
1967                         if (compare != 0) {
1968                                 regerror(compare, &reg, buffer, sizeof(buffer));
1969                                 fr_strerror_printf("Illegal regular expression in attribute: %s: %s",
1970                                            one->name, buffer);
1971                                 return -1;
1972                         }
1973
1974                         vp_prints_value(buffer, sizeof(buffer), two, 0);
1975
1976                         /*
1977                          *      Don't care about substring matches,
1978                          *      oh well...
1979                          */
1980                         compare = regexec(&reg, buffer, 0, NULL, 0);
1981
1982                         regfree(&reg);
1983                         if (one->operator == T_OP_REG_EQ) return (compare == 0);
1984                         return (compare != 0);
1985                 }
1986 #endif
1987
1988         default:                /* we're OK */
1989                 break;
1990         }
1991
1992         /*
1993          *      After doing the previous check for special comparisons,
1994          *      do the per-type comparison here.
1995          */
1996         switch (one->type) {
1997         case PW_TYPE_ABINARY:
1998         case PW_TYPE_OCTETS:
1999         {
2000                 size_t length;
2001
2002                 if (one->length < two->length) {
2003                         length = one->length;
2004                 } else {
2005                         length = two->length;
2006                 }
2007
2008                 if (length) {
2009                         compare = memcmp(two->vp_octets, one->vp_octets,
2010                                          length);
2011                         if (compare != 0) break;
2012                 }
2013
2014                 /*
2015                  *      Contents are the same.  The return code
2016                  *      is therefore the difference in lengths.
2017                  *
2018                  *      i.e. "0x00" is smaller than "0x0000"
2019                  */
2020                 compare = two->length - one->length;
2021         }
2022                 break;
2023
2024         case PW_TYPE_STRING:
2025                 compare = strcmp(two->vp_strvalue, one->vp_strvalue);
2026                 break;
2027
2028         case PW_TYPE_BYTE:
2029         case PW_TYPE_SHORT:
2030         case PW_TYPE_INTEGER:
2031         case PW_TYPE_DATE:
2032                 compare = two->vp_integer - one->vp_integer;
2033                 break;
2034
2035         case PW_TYPE_IPADDR:
2036                 compare = ntohl(two->vp_ipaddr) - ntohl(one->vp_ipaddr);
2037                 break;
2038
2039         case PW_TYPE_IPV6ADDR:
2040                 compare = memcmp(&two->vp_ipv6addr, &one->vp_ipv6addr,
2041                                  sizeof(two->vp_ipv6addr));
2042                 break;
2043
2044         case PW_TYPE_IPV6PREFIX:
2045                 compare = memcmp(&two->vp_ipv6prefix, &one->vp_ipv6prefix,
2046                                  sizeof(two->vp_ipv6prefix));
2047                 break;
2048
2049         case PW_TYPE_IFID:
2050                 compare = memcmp(&two->vp_ifid, &one->vp_ifid,
2051                                  sizeof(two->vp_ifid));
2052                 break;
2053
2054         default:
2055                 return 0;       /* unknown type */
2056         }
2057
2058         /*
2059          *      Now do the operator comparison.
2060          */
2061         switch (one->operator) {
2062         case T_OP_CMP_EQ:
2063                 return (compare == 0);
2064
2065         case T_OP_NE:
2066                 return (compare != 0);
2067
2068         case T_OP_LT:
2069                 return (compare < 0);
2070
2071         case T_OP_GT:
2072                 return (compare > 0);
2073
2074         case T_OP_LE:
2075                 return (compare <= 0);
2076
2077         case T_OP_GE:
2078                 return (compare >= 0);
2079
2080         default:
2081                 return 0;
2082         }
2083
2084         return 0;
2085 }