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