Set types correctly on talloced VALUE_PAIR buffers
[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 RCSID("$Id$")
24
25 #include <freeradius-devel/libradius.h>
26
27 #include <ctype.h>
28
29 #ifdef HAVE_PCREPOSIX_H
30 #  define WITH_REGEX
31 #  include <pcreposix.h>
32 #elif defined(HAVE_REGEX_H)
33 #  include <regex.h>
34 #  define WITH_REGEX
35
36 /*
37  *  For POSIX Regular expressions.
38  *  (0) Means no extended regular expressions.
39  *  REG_EXTENDED means use extended regular expressions.
40  */
41 #  ifndef REG_EXTENDED
42 #    define REG_EXTENDED (0)
43 #  endif
44
45 #  ifndef REG_NOSUB
46 #    define REG_NOSUB (0)
47 #  endif
48 #endif
49
50 #define attribute_eq(_x, _y) ((_x && _y) && (_x->da == _y->da) && (_x->tag == _y->tag))
51
52 /** Free a VALUE_PAIR
53  *
54  * @note Do not call directly, use talloc_free instead.
55  *
56  * @param vp to free.
57  * @return 0
58  */
59 static int _pairfree(VALUE_PAIR *vp) {
60         /*
61          *      The lack of DA means something has gone wrong
62          */
63         if (!vp->da) {
64                 fr_strerror_printf("VALUE_PAIR has NULL DICT_ATTR pointer (probably already freed)");
65         /*
66          *      Only free the DICT_ATTR if it was dynamically allocated
67          *      and was marked for free when the VALUE_PAIR is freed.
68          *
69          *      @fixme This is an awful hack and needs to be removed once DICT_ATTRs are allocated by talloc.
70          */
71         } else if (vp->da->flags.vp_free) {
72                 dict_attr_free(&(vp->da));
73         }
74
75 #ifndef NDEBUG
76         vp->vp_integer = FREE_MAGIC;
77 #endif
78
79 #ifdef TALLOC_DEBUG
80         talloc_report_depth_cb(NULL, 0, -1, fr_talloc_verify_cb, NULL);
81 #endif
82         return 0;
83 }
84
85 /** Dynamically allocate a new attribute
86  *
87  * Allocates a new attribute and a new dictionary attr if no DA is provided.
88  *
89  * @param[in] ctx for allocated memory, usually a pointer to a RADIUS_PACKET
90  * @param[in] da Specifies the dictionary attribute to build the VP from.
91  * @return a new value pair or NULL if an error occurred.
92  */
93 VALUE_PAIR *pairalloc(TALLOC_CTX *ctx, DICT_ATTR const *da)
94 {
95         VALUE_PAIR *vp;
96
97         /*
98          *      Caller must specify a da else we don't know what the attribute type is.
99          */
100         if (!da) {
101                 fr_strerror_printf("Invalid arguments");
102                 return NULL;
103         }
104
105         vp = talloc_zero(ctx, VALUE_PAIR);
106         if (!vp) {
107                 fr_strerror_printf("Out of memory");
108                 return NULL;
109         }
110
111         vp->da = da;
112         vp->op = T_OP_EQ;
113         vp->type = VT_NONE;
114
115         vp->length = da->flags.length;
116
117         talloc_set_destructor(vp, _pairfree);
118
119         return vp;
120 }
121
122 /** Create a new valuepair
123  *
124  * If attr and vendor match a dictionary entry then a VP with that DICT_ATTR
125  * will be returned.
126  *
127  * If attr or vendor are uknown will call dict_attruknown to create a dynamic
128  * DICT_ATTR of PW_TYPE_OCTETS.
129  *
130  * Which type of DICT_ATTR the VALUE_PAIR was created with can be determined by
131  * checking @verbatim vp->da->flags.is_unknown @endverbatim.
132  *
133  * @param[in] ctx for allocated memory, usually a pointer to a RADIUS_PACKET
134  * @param[in] attr number.
135  * @param[in] vendor number.
136  * @return the new valuepair or NULL on error.
137  */
138 VALUE_PAIR *paircreate(TALLOC_CTX *ctx, unsigned int attr, unsigned int vendor)
139 {
140         DICT_ATTR const *da;
141
142         da = dict_attrbyvalue(attr, vendor);
143         if (!da) {
144                 da = dict_attrunknown(attr, vendor, true);
145                 if (!da) {
146                         return NULL;
147                 }
148         }
149
150         return pairalloc(ctx, da);
151 }
152
153 /** Free memory used by a valuepair list.
154  *
155  * @todo TLV: needs to free all dependents of each VP freed.
156  */
157 void pairfree(VALUE_PAIR **vps)
158 {
159         VALUE_PAIR      *vp;
160         vp_cursor_t     cursor;
161
162         if (!vps || !*vps) {
163                 return;
164         }
165
166         for (vp = fr_cursor_init(&cursor, vps);
167              vp;
168              vp = fr_cursor_next(&cursor)) {
169                 VERIFY_VP(vp);
170                 talloc_free(vp);
171         }
172
173         *vps = NULL;
174 }
175
176 /** Mark malformed or unrecognised attributed as unknown
177  *
178  * @param vp to change DICT_ATTR of.
179  * @return 0 on success (or if already unknown) else -1 on error.
180  */
181 int pair2unknown(VALUE_PAIR *vp)
182 {
183         DICT_ATTR const *da;
184
185         VERIFY_VP(vp);
186         if (vp->da->flags.is_unknown) {
187                 return 0;
188         }
189
190         da = dict_attrunknown(vp->da->attr, vp->da->vendor, true);
191         if (!da) {
192                 return -1;
193         }
194
195         vp->da = da;
196
197         return 0;
198 }
199
200 /** Find the pair with the matching attribute
201  *
202  * @todo should take DAs and do a pointer comparison.
203  */
204 VALUE_PAIR *pairfind(VALUE_PAIR *vp, unsigned int attr, unsigned int vendor,
205                      int8_t tag)
206 {
207         vp_cursor_t     cursor;
208         VALUE_PAIR      *i;
209
210         for (i = fr_cursor_init(&cursor, &vp);
211              i;
212              i = fr_cursor_next(&cursor)) {
213                 VERIFY_VP(i);
214                 if ((i->da->attr == attr) && (i->da->vendor == vendor)
215                     && ((tag == TAG_ANY) || (i->da->flags.has_tag &&
216                         (i->tag == tag)))) {
217                         return i;
218                 }
219         }
220
221         return NULL;
222 }
223
224 /** Find the pair with the matching DAs
225  *
226  */
227 VALUE_PAIR *pairfind_da(VALUE_PAIR *vp, DICT_ATTR const *da, int8_t tag)
228 {
229         vp_cursor_t     cursor;
230         VALUE_PAIR      *i;
231
232         if(!fr_assert(da)) {
233                  return NULL;
234         }
235
236         for (i = fr_cursor_init(&cursor, &vp);
237              i;
238              i = fr_cursor_next(&cursor)) {
239                 VERIFY_VP(i);
240                 if ((i->da == da) && (!i->da->flags.has_tag || (tag == TAG_ANY) || (i->tag == tag))) {
241                         return i;
242                 }
243         }
244
245         return NULL;
246 }
247
248 /** Delete matching pairs
249  *
250  * Delete matching pairs from the attribute list.
251  *
252  * @param[in,out] first VP in list.
253  * @param[in] attr to match.
254  * @param[in] vendor to match.
255  * @param[in] tag to match. TAG_ANY matches any tag, TAG_UNUSED matches tagless VPs.
256  *
257  * @todo should take DAs and do a point comparison.
258  */
259 void pairdelete(VALUE_PAIR **first, unsigned int attr, unsigned int vendor,
260                 int8_t tag)
261 {
262         VALUE_PAIR *i, *next;
263         VALUE_PAIR **last = first;
264
265         for(i = *first; i; i = next) {
266                 VERIFY_VP(i);
267                 next = i->next;
268                 if ((i->da->attr == attr) && (i->da->vendor == vendor) &&
269                     ((tag == TAG_ANY) ||
270                      (i->da->flags.has_tag && (i->tag == tag)))) {
271                         *last = next;
272                         talloc_free(i);
273                 } else {
274                         last = &i->next;
275                 }
276         }
277 }
278
279 /** Add a VP to the end of the list.
280  *
281  * Locates the end of 'first', and links an additional VP 'add' at the end.
282  *
283  * @param[in] first VP in linked list. Will add new VP to the end of this list.
284  * @param[in] add VP to add to list.
285  */
286 void pairadd(VALUE_PAIR **first, VALUE_PAIR *add)
287 {
288         VALUE_PAIR *i;
289
290         if (!add) return;
291
292         VERIFY_VP(add);
293
294         if (*first == NULL) {
295                 *first = add;
296                 return;
297         }
298         for(i = *first; i->next; i = i->next)
299                 VERIFY_VP(i);
300         i->next = add;
301 }
302
303 /** Replace all matching VPs
304  *
305  * Walks over 'first', and replaces the first VP that matches 'replace'.
306  *
307  * @note Memory used by the VP being replaced will be freed.
308  * @note Will not work with unknown attributes.
309  *
310  * @param[in,out] first VP in linked list. Will search and replace in this list.
311  * @param[in] replace VP to replace.
312  */
313 void pairreplace(VALUE_PAIR **first, VALUE_PAIR *replace)
314 {
315         VALUE_PAIR *i, *next;
316         VALUE_PAIR **prev = first;
317
318         VERIFY_VP(replace);
319
320         if (*first == NULL) {
321                 *first = replace;
322                 return;
323         }
324
325         /*
326          *      Not an empty list, so find item if it is there, and
327          *      replace it. Note, we always replace the first one, and
328          *      we ignore any others that might exist.
329          */
330         for(i = *first; i; i = next) {
331                 VERIFY_VP(i);
332                 next = i->next;
333
334                 /*
335                  *      Found the first attribute, replace it,
336                  *      and return.
337                  */
338                 if ((i->da == replace->da) &&
339                     (!i->da->flags.has_tag || (i->tag == replace->tag))
340                 ) {
341                         *prev = replace;
342
343                         /*
344                          *      Should really assert that replace->next == NULL
345                          */
346                         replace->next = next;
347                         talloc_free(i);
348                         return;
349                 }
350
351                 /*
352                  *      Point to where the attribute should go.
353                  */
354                 prev = &i->next;
355         }
356
357         /*
358          *      If we got here, we didn't find anything to replace, so
359          *      stopped at the last item, which we just append to.
360          */
361         *prev = replace;
362 }
363
364 static void pairsort_split(VALUE_PAIR *source, VALUE_PAIR **front, VALUE_PAIR **back)
365 {
366         VALUE_PAIR *fast;
367         VALUE_PAIR *slow;
368
369         /*
370          *      Stopping condition - no more elements left to split
371          */
372         if (!source || !source->next) {
373                 *front = source;
374                 *back = NULL;
375
376                 return;
377         }
378
379         /*
380          *      Fast advances twice as fast as slow, so when it gets to the end,
381          *      slow will point to the middle of the linked list.
382          */
383         slow = source;
384         fast = source->next;
385
386         while (fast) {
387                 fast = fast->next;
388                 if (fast) {
389                         slow = slow->next;
390                         fast = fast->next;
391                 }
392         }
393
394         *front = source;
395         *back = slow->next;
396         slow->next = NULL;
397 }
398
399 static VALUE_PAIR *pairsort_merge(VALUE_PAIR *a, VALUE_PAIR *b, bool with_tag)
400 {
401         VALUE_PAIR *result = NULL;
402
403         if (!a) return b;
404         if (!b) return a;
405
406         /*
407          *      Compare the DICT_ATTRs and tags
408          */
409         if ((with_tag && (a->tag < b->tag)) || (a->da <= b->da)) {
410                 result = a;
411                 result->next = pairsort_merge(a->next, b, with_tag);
412         } else {
413                 result = b;
414                 result->next = pairsort_merge(a, b->next, with_tag);
415         }
416
417         return result;
418 }
419
420 /** Sort a linked list of VALUE_PAIRs using merge sort
421  *
422  * @param[in,out] vps List of VALUE_PAIRs to sort.
423  * @param[in] with_tag sort by tag then by DICT_ATTR
424  */
425 void pairsort(VALUE_PAIR **vps, bool with_tag)
426 {
427         VALUE_PAIR *head = *vps;
428         VALUE_PAIR *a;
429         VALUE_PAIR *b;
430
431         /*
432          *      If there's 0-1 elements it must already be sorted.
433          */
434         if (!head || !head->next) {
435                 return;
436         }
437
438         pairsort_split(head, &a, &b);   /* Split into sublists */
439         pairsort(&a, with_tag);         /* Traverse left */
440         pairsort(&b, with_tag);         /* Traverse right */
441
442         /*
443          *      merge the two sorted lists together
444          */
445         *vps = pairsort_merge(a, b, with_tag);
446 }
447
448 /** Uses paircmp to verify all VALUE_PAIRs in list match the filter defined by check
449  *
450  * @param filter attributes to check list against.
451  * @param list attributes, probably a request or reply
452  */
453 bool pairvalidate(VALUE_PAIR *filter, VALUE_PAIR *list)
454 {
455         vp_cursor_t filter_cursor;
456         vp_cursor_t list_cursor;
457
458         VALUE_PAIR *check, *match;
459
460         if (!filter && !list) {
461                 return true;
462         }
463         if (!filter || !list) {
464                 return false;
465         }
466
467         /*
468          *      This allows us to verify the sets of validate and reply are equal
469          *      i.e. we have a validate rule which matches every reply attribute.
470          *
471          *      @todo this should be removed one we have sets and lists
472          */
473         pairsort(&filter, true);
474         pairsort(&list, true);
475
476         match = fr_cursor_init(&list_cursor, &list);
477         check = fr_cursor_init(&filter_cursor, &filter);
478
479         while (true) {
480                 /*
481                  *      The lists are sorted, so if the first
482                  *      attributes aren't of the same type, then we're
483                  *      done.
484                  */
485                 if (!attribute_eq(check, match)) {
486                         return false;
487                 }
488
489                 /*
490                  *      They're of the same type, but don't have the
491                  *      same values.  This is a problem.
492                  *
493                  *      Note that the RFCs say that for attributes of
494                  *      the same type, order is important.
495                  */
496                 if (!paircmp(check, match)) {
497                         return false;
498                 }
499
500                 match = fr_cursor_next(&list_cursor);
501                 check = fr_cursor_next(&filter_cursor);
502
503                 if (!match && !check) break;
504
505                 /*
506                  *      One list ended earlier than the others, they
507                  *      didn't match.
508                  */
509                 if (!match || !check) {
510                         return false;
511                 }
512         }
513
514         return true;
515 }
516
517 /** Copy a single valuepair
518  *
519  * Allocate a new valuepair and copy the da from the old vp.
520  *
521  * @param[in] ctx for talloc
522  * @param[in] vp to copy.
523  * @return a copy of the input VP or NULL on error.
524  */
525 VALUE_PAIR *paircopyvp(TALLOC_CTX *ctx, VALUE_PAIR const *vp)
526 {
527         VALUE_PAIR *n;
528
529         if (!vp) return NULL;
530
531         VERIFY_VP(vp);
532
533         n = pairalloc(ctx, vp->da);
534         if (!n) return NULL;
535
536         memcpy(n, vp, sizeof(*n));
537
538         /*
539          *      Now copy the value
540          */
541         if (vp->type == VT_XLAT) {
542                 n->value.xlat = talloc_typed_strdup(n, n->value.xlat);
543         }
544
545         n->da = dict_attr_copy(vp->da, true);
546         if (!n->da) {
547                 talloc_free(n);
548                 return NULL;
549         }
550
551         n->next = NULL;
552
553         if (n->data.ptr) switch (n->da->type) {
554         case PW_TYPE_TLV:
555         case PW_TYPE_OCTETS:
556                 n->vp_octets = talloc_memdup(n, vp->vp_octets, n->length);
557                 talloc_set_type(n->vp_octets, uint8_t);
558                 break;
559
560         case PW_TYPE_STRING:
561                 n->vp_strvalue = talloc_memdup(n, vp->vp_strvalue, n->length + 1);      /* NULL byte */
562                 talloc_set_type(n->vp_strvalue, char);
563                 break;
564
565         default:
566                 break;
567         }
568
569         return n;
570 }
571
572 /** Copy data from one VP to another
573  *
574  * Allocate a new pair using da, and copy over the value from the specified
575  * vp.
576  *
577  * @todo Should be able to do type conversions.
578  *
579  * @param[in] ctx for talloc
580  * @param[in] da of new attribute to alloc.
581  * @param[in] vp to copy data from.
582  * @return the new valuepair.
583  */
584 VALUE_PAIR *paircopyvpdata(TALLOC_CTX *ctx, DICT_ATTR const *da, VALUE_PAIR const *vp)
585 {
586         VALUE_PAIR *n;
587
588         if (!vp) return NULL;
589
590         VERIFY_VP(vp);
591
592         /*
593          *      The types have to be identical, OR the "from" VP has
594          *      to be octets.
595          */
596         if (da->type != vp->da->type) {
597                 int length;
598                 uint8_t *p;
599                 VALUE_PAIR const **pvp;
600
601                 if (vp->da->type == PW_TYPE_OCTETS) {
602                         /*
603                          *      Decode the data.  It may be wrong!
604                          */
605                         if (rad_data2vp(da->attr, da->vendor, vp->vp_octets, vp->length, &n) < 0) {
606                                 return NULL;
607                         }
608
609                         n->type = VT_DATA;
610                         return n;
611                 }
612
613                 /*
614                  *      Else the destination type is octets
615                  */
616                 switch (vp->da->type) {
617                 default:
618                         return NULL; /* can't do it */
619
620                 case PW_TYPE_INTEGER:
621                 case PW_TYPE_IPADDR:
622                 case PW_TYPE_DATE:
623                 case PW_TYPE_IFID:
624                 case PW_TYPE_IPV6ADDR:
625                 case PW_TYPE_IPV6PREFIX:
626                 case PW_TYPE_BYTE:
627                 case PW_TYPE_SHORT:
628                 case PW_TYPE_ETHERNET:
629                 case PW_TYPE_SIGNED:
630                 case PW_TYPE_INTEGER64:
631                 case PW_TYPE_IPV4PREFIX:
632                         break;
633                 }
634
635                 n = pairalloc(ctx, da);
636                 if (!n) return NULL;
637
638                 p = talloc_array(n, uint8_t, dict_attr_sizes[vp->da->type][1] + 2);
639
640                 pvp = &vp;
641                 length = rad_vp2attr(NULL, NULL, NULL, pvp, p, dict_attr_sizes[vp->da->type][1]);
642                 if (length < 0) {
643                         pairfree(&n);
644                         return NULL;
645                 }
646
647                 pairmemcpy(n, p + 2, length - 2);
648                 talloc_free(p);
649                 return n;
650         }
651
652         n = pairalloc(ctx, da);
653         if (!n) return NULL;
654
655         memcpy(n, vp, sizeof(*n));
656         n->da = da;
657
658         if (n->type == VT_XLAT) {
659                 n->value.xlat = talloc_typed_strdup(n, n->value.xlat);
660         }
661
662         if (n->data.ptr) switch (n->da->type) {
663         case PW_TYPE_TLV:
664         case PW_TYPE_OCTETS:
665                 n->vp_octets = talloc_memdup(n, vp->vp_octets, n->length);
666                 talloc_set_type(n->vp_octets, uint8_t);
667                 break;
668
669         case PW_TYPE_STRING:
670                 n->vp_strvalue = talloc_memdup(n, vp->vp_strvalue, n->length + 1);      /* NULL byte */
671                 talloc_set_type(n->vp_strvalue, char);
672                 break;
673
674         default:
675                 break;
676         }
677
678         n->next = NULL;
679
680         return n;
681 }
682
683
684 /** Copy matching pairs
685  *
686  * Copy pairs of a matching attribute number, vendor number and tag from the
687  * the input list to a new list, and returns the head of this list.
688  *
689  * @param[in] ctx for talloc
690  * @param[in] from whence to copy VALUE_PAIRs.
691  * @param[in] attr to match, if 0 input list will not be filtered by attr.
692  * @param[in] vendor to match.
693  * @param[in] tag to match, TAG_ANY matches any tag, TAG_UNUSED matches tagless VPs.
694  * @return the head of the new VALUE_PAIR list or NULL on error.
695  */
696 VALUE_PAIR *paircopy2(TALLOC_CTX *ctx, VALUE_PAIR *from,
697                       unsigned int attr, unsigned int vendor, int8_t tag)
698 {
699         vp_cursor_t src, dst;
700
701         VALUE_PAIR *out = NULL, *vp;
702
703         fr_cursor_init(&dst, &out);
704         for (vp = fr_cursor_init(&src, &from);
705              vp;
706              vp = fr_cursor_next(&src)) {
707                 VERIFY_VP(vp);
708
709                 if ((vp->da->attr != attr) || (vp->da->vendor != vendor)) {
710                         continue;
711                 }
712
713                 if ((tag != TAG_ANY) && vp->da->flags.has_tag && (vp->tag != tag)) {
714                         continue;
715                 }
716
717                 vp = paircopyvp(ctx, vp);
718                 if (!vp) {
719                         pairfree(&out);
720                         return NULL;
721                 }
722                 fr_cursor_insert(&dst, vp);
723         }
724
725         return out;
726 }
727
728
729 /** Copy a pairlist.
730  *
731  * Copy all pairs from 'from' regardless of tag, attribute or vendor.
732  *
733  * @param[in] ctx for new VALUE_PAIRs to be allocated in.
734  * @param[in] from whence to copy VALUE_PAIRs.
735  * @return the head of the new VALUE_PAIR list or NULL on error.
736  */
737 VALUE_PAIR *paircopy(TALLOC_CTX *ctx, VALUE_PAIR *from)
738 {
739         vp_cursor_t src, dst;
740
741         VALUE_PAIR *out = NULL, *vp;
742
743         fr_cursor_init(&dst, &out);
744         for (vp = fr_cursor_init(&src, &from);
745              vp;
746              vp = fr_cursor_next(&src)) {
747                 VERIFY_VP(vp);
748                 vp = paircopyvp(ctx, vp);
749                 if (!vp) {
750                         pairfree(&out);
751                         return NULL;
752                 }
753                 fr_cursor_insert(&dst, vp); /* paircopy sets next pointer to NULL */
754         }
755
756         return out;
757 }
758
759 /** Move pairs from source list to destination list respecting operator
760  *
761  * @note This function does some additional magic that's probably not needed
762  *       in most places. Consider using radius_pairmove in server code.
763  *
764  * @note pairfree should be called on the head of the source list to free
765  *       unmoved attributes (if they're no longer needed).
766  *
767  * @note Does not respect tags when matching.
768  *
769  * @param[in] ctx for talloc
770  * @param[in,out] to destination list.
771  * @param[in,out] from source list.
772  *
773  * @see radius_pairmove
774  */
775 void pairmove(TALLOC_CTX *ctx, VALUE_PAIR **to, VALUE_PAIR **from)
776 {
777         VALUE_PAIR *i, *found;
778         VALUE_PAIR *head_new, **tail_new;
779         VALUE_PAIR **tail_from;
780
781         if (!to || !from || !*from) return;
782
783         /*
784          *      We're editing the "to" list while we're adding new
785          *      attributes to it.  We don't want the new attributes to
786          *      be edited, so we create an intermediate list to hold
787          *      them during the editing process.
788          */
789         head_new = NULL;
790         tail_new = &head_new;
791
792         /*
793          *      We're looping over the "from" list, moving some
794          *      attributes out, but leaving others in place.
795          */
796         tail_from = from;
797         while ((i = *tail_from) != NULL) {
798                 VERIFY_VP(i);
799
800                 /*
801                  *      We never move Fall-Through.
802                  */
803                 if (!i->da->vendor && i->da->attr == PW_FALL_THROUGH) {
804                         tail_from = &(i->next);
805                         continue;
806                 }
807
808                 /*
809                  *      Unlike previous versions, we treat all other
810                  *      attributes as normal.  i.e. there's no special
811                  *      treatment for passwords or Hint.
812                  */
813
814                 switch (i->op) {
815                         /*
816                          *      Anything else are operators which
817                          *      shouldn't occur.  We ignore them, and
818                          *      leave them in place.
819                          */
820                         default:
821                                 tail_from = &(i->next);
822                                 continue;
823
824                         /*
825                          *      Add it to the "to" list, but only if
826                          *      it doesn't already exist.
827                          */
828                         case T_OP_EQ:
829                                 found = pairfind(*to, i->da->attr, i->da->vendor,
830                                                  TAG_ANY);
831                                 if (!found) goto do_add;
832
833                                 tail_from = &(i->next);
834                                 continue;
835
836                         /*
837                          *      Add it to the "to" list, and delete any attribute
838                          *      of the same vendor/attr which already exists.
839                          */
840                         case T_OP_SET:
841                                 found = pairfind(*to, i->da->attr, i->da->vendor,
842                                                  TAG_ANY);
843                                 if (!found) goto do_add;
844
845                                 /*
846                                  *      Do NOT call pairdelete() here,
847                                  *      due to issues with re-writing
848                                  *      "request->username".
849                                  *
850                                  *      Everybody calls pairmove, and
851                                  *      expects it to work.  We can't
852                                  *      update request->username here,
853                                  *      so instead we over-write the
854                                  *      vp that it's pointing to.
855                                  */
856                                 switch (found->da->type) {
857                                         VALUE_PAIR *j;
858
859                                         default:
860                                                 j = found->next;
861                                                 memcpy(found, i, sizeof(*found));
862                                                 found->next = j;
863                                                 break;
864
865                                         case PW_TYPE_TLV:
866                                                 pairmemsteal(found, i->vp_tlv);
867                                                 i->vp_tlv = NULL;
868                                                 break;
869
870                                         case PW_TYPE_OCTETS:
871                                                 pairmemsteal(found, i->vp_octets);
872                                                 i->vp_octets = NULL;
873                                                 break;
874
875                                         case PW_TYPE_STRING:
876                                                 pairstrsteal(found, i->vp_strvalue);
877                                                 i->vp_strvalue = NULL;
878                                                 found->tag = i->tag;
879                                                 break;
880                                 }
881
882                                 /*
883                                  *      Delete *all* of the attributes
884                                  *      of the same number.
885                                  */
886                                 pairdelete(&found->next,
887                                            found->da->attr,
888                                            found->da->vendor, TAG_ANY);
889
890                                 /*
891                                  *      Remove this attribute from the
892                                  *      "from" list.
893                                  */
894                                 *tail_from = i->next;
895                                 i->next = NULL;
896                                 pairfree(&i);
897                                 continue;
898
899                         /*
900                          *      Move it from the old list and add it
901                          *      to the new list.
902                          */
903                         case T_OP_ADD:
904                 do_add:
905                                 *tail_from = i->next;
906                                 i->next = NULL;
907                                 *tail_new = talloc_steal(ctx, i);
908                                 tail_new = &(i->next);
909                                 continue;
910                 }
911         } /* loop over the "from" list. */
912
913         /*
914          *      Take the "new" list, and append it to the "to" list.
915          */
916         pairadd(to, head_new);
917 }
918
919 /** Move matching pairs between VALUE_PAIR lists
920  *
921  * Move pairs of a matching attribute number, vendor number and tag from the
922  * the input list to the output list.
923  *
924  * @note pairfree should be called on the head of the old list to free unmoved
925          attributes (if they're no longer needed).
926  *
927  * @param[in] ctx for talloc
928  * @param[in,out] to destination list.
929  * @param[in,out] from source list.
930  * @param[in] attr to match, if PW_VENDOR_SPECIFIC and vendor 0, only VSAs will
931  *            be copied.  If 0 and 0, all attributes will match
932  * @param[in] vendor to match.
933  * @param[in] tag to match, TAG_ANY matches any tag, TAG_UNUSED matches tagless VPs.
934  */
935 void pairfilter(TALLOC_CTX *ctx, VALUE_PAIR **to, VALUE_PAIR **from, unsigned int attr, unsigned int vendor, int8_t tag)
936 {
937         VALUE_PAIR *to_tail, *i, *next;
938         VALUE_PAIR *iprev = NULL;
939
940         /*
941          *      Find the last pair in the "to" list and put it in "to_tail".
942          *
943          *      @todo: replace the "if" with "VALUE_PAIR **tail"
944          */
945         if (*to != NULL) {
946                 to_tail = *to;
947                 for(i = *to; i; i = i->next) {
948                         VERIFY_VP(i);
949                         to_tail = i;
950                 }
951         } else
952                 to_tail = NULL;
953
954         /*
955          *      Attr/vendor of 0 means "move them all".
956          *      It's better than "pairadd(foo,bar);bar=NULL"
957          */
958         if ((vendor == 0) && (attr == 0)) {
959                 if (*to) {
960                         to_tail->next = *from;
961                 } else {
962                         *to = *from;
963                 }
964
965                 for (i = *from; i; i = i->next) {
966                         (void) talloc_steal(ctx, i);
967                 }
968
969                 *from = NULL;
970                 return;
971         }
972
973         for(i = *from; i; i = next) {
974                 VERIFY_VP(i);
975                 next = i->next;
976
977                 if ((tag != TAG_ANY) && i->da->flags.has_tag &&
978                     (i->tag != tag)) {
979                         continue;
980                 }
981
982                 /*
983                  *      vendor=0, attr = PW_VENDOR_SPECIFIC means
984                  *      "match any vendor attribute".
985                  */
986                 if ((vendor == 0) && (attr == PW_VENDOR_SPECIFIC)) {
987                         /*
988                          *      It's a VSA: move it over.
989                          */
990                         if (i->da->vendor != 0) goto move;
991
992                         /*
993                          *      It's Vendor-Specific: move it over.
994                          */
995                         if (i->da->attr == attr) goto move;
996
997                         /*
998                          *      It's not a VSA: ignore it.
999                          */
1000                         iprev = i;
1001                         continue;
1002                 }
1003
1004                 /*
1005                  *      If it isn't an exact match, ignore it.
1006                  */
1007                 if (!((i->da->vendor == vendor) && (i->da->attr == attr))) {
1008                         iprev = i;
1009                         continue;
1010                 }
1011
1012         move:
1013                 /*
1014                  *      Remove the attribute from the "from" list.
1015                  */
1016                 if (iprev)
1017                         iprev->next = next;
1018                 else
1019                         *from = next;
1020
1021                 /*
1022                  *      Add the attribute to the "to" list.
1023                  */
1024                 if (to_tail)
1025                         to_tail->next = i;
1026                 else
1027                         *to = i;
1028                 to_tail = i;
1029                 i->next = NULL;
1030                 (void) talloc_steal(ctx, i);
1031         }
1032 }
1033
1034 static char const *hextab = "0123456789abcdef";
1035
1036 bool pairparsevalue(VALUE_PAIR *vp, char const *value)
1037 {
1038         char            *p;
1039         char const      *cp, *cs;
1040         int             x;
1041         uint64_t        y;
1042         size_t          length;
1043         DICT_VALUE      *dval;
1044
1045         if (!value) return false;
1046         VERIFY_VP(vp);
1047
1048         /*
1049          *      It's a comparison, not a real VALUE_PAIR, copy the string over verbatim
1050          */
1051         if ((vp->op == T_OP_REG_EQ) || (vp->op == T_OP_REG_NE)) {
1052                 pairstrcpy(vp, value);  /* Icky hacky ewww */
1053                 goto finish;
1054         }
1055
1056         switch(vp->da->type) {
1057         case PW_TYPE_STRING:
1058                 /*
1059                  *      Do escaping here
1060                  */
1061                 p = talloc_typed_strdup(vp, value);
1062                 vp->vp_strvalue = p;
1063                 cp = value;
1064                 length = 0;
1065
1066                 while (*cp) {
1067                         char c = *cp++;
1068
1069                         if (c == '\\') {
1070                                 switch (*cp) {
1071                                 case 'r':
1072                                         c = '\r';
1073                                         cp++;
1074                                         break;
1075                                 case 'n':
1076                                         c = '\n';
1077                                         cp++;
1078                                         break;
1079                                 case 't':
1080                                         c = '\t';
1081                                         cp++;
1082                                         break;
1083                                 case '"':
1084                                         c = '"';
1085                                         cp++;
1086                                         break;
1087                                 case '\'':
1088                                         c = '\'';
1089                                         cp++;
1090                                         break;
1091                                 case '\\':
1092                                         c = '\\';
1093                                         cp++;
1094                                         break;
1095                                 case '`':
1096                                         c = '`';
1097                                         cp++;
1098                                         break;
1099                                 case '\0':
1100                                         c = '\\'; /* no cp++ */
1101                                         break;
1102                                 default:
1103                                         if ((cp[0] >= '0') &&
1104                                             (cp[0] <= '9') &&
1105                                             (cp[1] >= '0') &&
1106                                             (cp[1] <= '9') &&
1107                                             (cp[2] >= '0') &&
1108                                             (cp[2] <= '9') &&
1109                                             (sscanf(cp, "%3o", &x) == 1)) {
1110                                                 c = x;
1111                                                 cp += 3;
1112
1113                                         } else if (cp[0]) {
1114                                                 /*
1115                                                  *      \p --> p
1116                                                  */
1117                                                 c = *cp++;
1118                                         } /* else at EOL \ --> \ */
1119                                 }
1120                         }
1121                         *p++ = c;
1122                         length++;
1123                 }
1124                 *p = '\0';
1125                 vp->length = length;
1126                 break;
1127
1128         case PW_TYPE_IPADDR:
1129                 /*
1130                  *      FIXME: complain if hostname
1131                  *      cannot be resolved, or resolve later!
1132                  */
1133                 p = NULL;
1134                 {
1135                         fr_ipaddr_t ipaddr;
1136                         char ipv4[16];
1137
1138                         /*
1139                          *      Convert things which are obviously integers to IP addresses
1140                          *
1141                          *      We assume the number is the bigendian representation of the
1142                          *      IP address.
1143                          */
1144                         if (fr_integer_check(value)) {
1145                                 vp->vp_ipaddr = htonl(atol(value));
1146                                 break;
1147                         }
1148
1149                         /*
1150                          *      Certain applications/databases print IPv4 addresses with a
1151                          *      /32 suffix. Strip it off if the mask is 32, else error out.
1152                          */
1153                         p = strchr(value, '/');
1154                         if (p) {
1155                                 if ((p[1] != '3') || (p[2] != '2') || (p[3] != '\0')) {
1156                                         fr_strerror_printf("Invalid IP address suffix \"%s\".  Only '/32' permitted "
1157                                                            "for non-prefix types", p);
1158                                         return false;
1159                                 }
1160
1161                                 strlcpy(ipv4, value, sizeof(ipv4));
1162                                 ipv4[p - value] = '\0';
1163                                 cs = ipv4;
1164                         } else {
1165                                 cs = value;
1166                         }
1167
1168                         if (ip_hton(cs, AF_INET, &ipaddr) < 0) {
1169                                 fr_strerror_printf("Failed to find IP address for %s", cs);
1170                                 return false;
1171                         }
1172
1173                         vp->vp_ipaddr = ipaddr.ipaddr.ip4addr.s_addr;
1174                 }
1175                 vp->length = 4;
1176                 break;
1177
1178         case PW_TYPE_BYTE:
1179                 vp->length = 1;
1180
1181                 /*
1182                  *      Note that ALL integers are unsigned!
1183                  */
1184                 vp->vp_integer = fr_strtoul(value, &p);
1185                 if (!*p) {
1186                         if (vp->vp_integer > 255) {
1187                                 fr_strerror_printf("Byte value \"%s\" is larger than 255", value);
1188                                 return false;
1189                         }
1190                         break;
1191                 }
1192                 if (fr_whitespace_check(p)) break;
1193                 goto check_for_value;
1194
1195         case PW_TYPE_SHORT:
1196                 /*
1197                  *      Note that ALL integers are unsigned!
1198                  */
1199                 vp->vp_integer = fr_strtoul(value, &p);
1200                 vp->length = 2;
1201                 if (!*p) {
1202                         if (vp->vp_integer > 65535) {
1203                                 fr_strerror_printf("Byte value \"%s\" is larger than 65535", value);
1204                                 return false;
1205                         }
1206                         break;
1207                 }
1208                 if (fr_whitespace_check(p)) break;
1209                 goto check_for_value;
1210
1211         case PW_TYPE_INTEGER:
1212                 /*
1213                  *      Note that ALL integers are unsigned!
1214                  */
1215                 vp->vp_integer = fr_strtoul(value, &p);
1216                 vp->length = 4;
1217                 if (!*p) break;
1218                 if (fr_whitespace_check(p)) break;
1219
1220         check_for_value:
1221                 /*
1222                  *      Look for the named value for the given
1223                  *      attribute.
1224                  */
1225                 if ((dval = dict_valbyname(vp->da->attr, vp->da->vendor, value)) == NULL) {
1226                         fr_strerror_printf("Unknown value '%s' for attribute '%s'", value, vp->da->name);
1227                         return false;
1228                 }
1229                 vp->vp_integer = dval->value;
1230                 break;
1231
1232         case PW_TYPE_INTEGER64:
1233                 /*
1234                  *      Note that ALL integers are unsigned!
1235                  */
1236                 if (sscanf(value, "%" PRIu64, &y) != 1) {
1237                         fr_strerror_printf("Invalid value '%s' for attribute '%s'",
1238                                            value, vp->da->name);
1239                         return false;
1240                 }
1241                 vp->vp_integer64 = y;
1242                 vp->length = 8;
1243                 length = strspn(value, "0123456789");
1244                 if (fr_whitespace_check(value + length)) break;
1245                 break;
1246
1247         case PW_TYPE_DATE:
1248                 {
1249                         /*
1250                          *      time_t may be 64 bits, whule vp_date
1251                          *      MUST be 32-bits.  We need an
1252                          *      intermediary variable to handle
1253                          *      the conversions.
1254                          */
1255                         time_t date;
1256
1257                         if (fr_get_time(value, &date) < 0) {
1258                                 fr_strerror_printf("failed to parse time string "
1259                                            "\"%s\"", value);
1260                                 return false;
1261                         }
1262
1263                         vp->vp_date = date;
1264                 }
1265                 vp->length = 4;
1266                 break;
1267
1268         case PW_TYPE_ABINARY:
1269 #ifdef WITH_ASCEND_BINARY
1270                 if (strncasecmp(value, "0x", 2) == 0) {
1271                         goto do_octets;
1272                 }
1273
1274                 if (ascend_parse_filter(vp, value) < 0 ) {
1275                         /* Allow ascend_parse_filter's strerror to bubble up */
1276                         return false;
1277                 }
1278                 break;
1279
1280                 /*
1281                  *      If Ascend binary is NOT defined,
1282                  *      then fall through to raw octets, so that
1283                  *      the user can at least make them by hand...
1284                  */
1285 #endif
1286         /* raw octets: 0x01020304... */
1287         case PW_TYPE_VSA:
1288                 if (strcmp(value, "ANY") == 0) {
1289                         vp->length = 0;
1290                         break;
1291                 } /* else it's hex */
1292
1293         case PW_TYPE_OCTETS:
1294                 if (strncasecmp(value, "0x", 2) == 0) {
1295                         size_t size;
1296                         uint8_t *us;
1297
1298 #ifdef WITH_ASCEND_BINARY
1299                 do_octets:
1300 #endif
1301                         cp = value + 2;
1302                         size = strlen(cp);
1303                         vp->length = size >> 1;
1304                         us = talloc_array(vp, uint8_t, vp->length);
1305
1306                         /*
1307                          *      Invalid.
1308                          */
1309                         if ((size & 0x01) != 0) {
1310                                 fr_strerror_printf("Hex string is not an even length string");
1311                                 return false;
1312                         }
1313
1314                         if (fr_hex2bin(us, cp, vp->length) != vp->length) {
1315                                 fr_strerror_printf("Invalid hex data");
1316                                 return false;
1317                         }
1318                         vp->vp_octets = us;
1319                 } else {
1320                         pairstrcpy(vp, value);
1321                         talloc_set_type(vp->vp_octets, uint8_t);        /* fixup type */
1322                 }
1323                 break;
1324
1325         case PW_TYPE_IFID:
1326                 if (ifid_aton(value, (void *) &vp->vp_ifid) == NULL) {
1327                         fr_strerror_printf("Failed to parse interface-id string \"%s\"", value);
1328                         return false;
1329                 }
1330                 vp->length = 8;
1331                 break;
1332
1333         case PW_TYPE_IPV6ADDR:
1334                 {
1335                         fr_ipaddr_t ipaddr;
1336
1337                         if (ip_hton(value, AF_INET6, &ipaddr) < 0) {
1338                                 char buffer[1024];
1339
1340                                 strlcpy(buffer, fr_strerror(), sizeof(buffer));
1341
1342                                 fr_strerror_printf("failed to parse IPv6 address "
1343                                                    "string \"%s\": %s", value, buffer);
1344                                 return false;
1345                         }
1346                         vp->vp_ipv6addr = ipaddr.ipaddr.ip6addr;
1347                         vp->length = 16; /* length of IPv6 address */
1348                 }
1349                 break;
1350
1351         case PW_TYPE_IPV6PREFIX:
1352                 p = strchr(value, '/');
1353                 if (!p || ((p - value) >= 256)) {
1354                         fr_strerror_printf("invalid IPv6 prefix string \"%s\"", value);
1355                         return false;
1356                 } else {
1357                         unsigned int prefix;
1358                         char buffer[256], *eptr;
1359
1360                         memcpy(buffer, value, p - value);
1361                         buffer[p - value] = '\0';
1362
1363                         if (inet_pton(AF_INET6, buffer, vp->vp_ipv6prefix + 2) <= 0) {
1364                                 fr_strerror_printf("failed to parse IPv6 address string \"%s\"", value);
1365                                 return false;
1366                         }
1367
1368                         prefix = strtoul(p + 1, &eptr, 10);
1369                         if ((prefix > 128) || *eptr) {
1370                                 fr_strerror_printf("failed to parse IPv6 address string \"%s\"", value);
1371                                 return false;
1372                         }
1373                         vp->vp_ipv6prefix[1] = prefix;
1374
1375                         if (prefix < 128) {
1376                                 struct in6_addr addr;
1377
1378                                 addr = fr_ipaddr_mask6((struct in6_addr *)(&vp->vp_ipv6prefix[2]), prefix);
1379                                 memcpy(vp->vp_ipv6prefix + 2, &addr, sizeof(addr));
1380                         }
1381                 }
1382                 vp->length = 16 + 2;
1383                 break;
1384
1385         case PW_TYPE_IPV4PREFIX:
1386                 p = strchr(value, '/');
1387
1388                 /*
1389                  *      192.0.2.2 is parsed as if it was /32
1390                  */
1391                 if (!p) {
1392                         vp->vp_ipv4prefix[1] = 32;
1393
1394                         if (inet_pton(AF_INET, value, vp->vp_ipv4prefix + 2) <= 0) {
1395                                 fr_strerror_printf("failed to parse IPv4 address string \"%s\"", value);
1396                                 return false;
1397                         }
1398                         vp->length = sizeof(vp->vp_ipv4prefix);
1399                         break;
1400                 }
1401
1402                 /*
1403                  *      Otherwise parse the prefix
1404                  */
1405                 if ((p - value) >= 256) {
1406                         fr_strerror_printf("invalid IPv4 prefix string \"%s\"", value);
1407                         return false;
1408                 } else {
1409                         unsigned int prefix;
1410                         char buffer[256], *eptr;
1411
1412                         memcpy(buffer, value, p - value);
1413                         buffer[p - value] = '\0';
1414
1415                         if (inet_pton(AF_INET, buffer, vp->vp_ipv4prefix + 2) <= 0) {
1416                                 fr_strerror_printf("failed to parse IPv4 address string \"%s\"", value);
1417                                 return false;
1418                         }
1419
1420                         prefix = strtoul(p + 1, &eptr, 10);
1421                         if ((prefix > 32) || *eptr) {
1422                                 fr_strerror_printf("failed to parse IPv4 address string \"%s\"", value);
1423                                 return false;
1424                         }
1425                         vp->vp_ipv4prefix[1] = prefix;
1426
1427                         if (prefix < 32) {
1428                                 struct in_addr addr;
1429
1430                                 addr = fr_ipaddr_mask((struct in_addr *)(&vp->vp_ipv4prefix[2]), prefix);
1431                                 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
1432                         }
1433                 }
1434                 vp->length = sizeof(vp->vp_ipv4prefix);
1435                 break;
1436
1437         case PW_TYPE_ETHERNET:
1438                 {
1439                         char const *c1, *c2;
1440
1441                         /*
1442                          *      Convert things which are obviously integers to Ethernet addresses
1443                          *
1444                          *      We assume the number is the bigendian representation of the
1445                          *      ethernet address.
1446                          */
1447                         if (fr_integer_check(value)) {
1448                                 uint64_t integer = htonll(atoll(value));
1449
1450                                 memcpy(&vp->vp_ether, &integer, sizeof(vp->vp_ether));
1451                                 break;
1452                         }
1453
1454                         length = 0;
1455                         cp = value;
1456                         while (*cp) {
1457                                 if (cp[1] == ':') {
1458                                         c1 = hextab;
1459                                         c2 = memchr(hextab, tolower((int) cp[0]), 16);
1460                                         cp += 2;
1461                                 } else if ((cp[1] != '\0') &&
1462                                            ((cp[2] == ':') ||
1463                                             (cp[2] == '\0'))) {
1464                                            c1 = memchr(hextab, tolower((int) cp[0]), 16);
1465                                            c2 = memchr(hextab, tolower((int) cp[1]), 16);
1466                                            cp += 2;
1467                                            if (*cp == ':') cp++;
1468                                 } else {
1469                                         c1 = c2 = NULL;
1470                                 }
1471                                 if (!c1 || !c2 || (length >= sizeof(vp->vp_ether))) {
1472                                         fr_strerror_printf("failed to parse Ethernet address \"%s\"", value);
1473                                         return false;
1474                                 }
1475                                 vp->vp_ether[length] = ((c1-hextab)<<4) + (c2-hextab);
1476                                 length++;
1477                         }
1478                 }
1479                 vp->length = 6;
1480                 break;
1481
1482         /*
1483          *      Crazy polymorphic (IPv4/IPv6) attribute type for WiMAX.
1484          *
1485          *      We try and make is saner by replacing the original
1486          *      da, with either an IPv4 or IPv6 da type.
1487          *
1488          *      These are not dynamic da, and will have the same vendor
1489          *      and attribute as the original.
1490          */
1491         case PW_TYPE_COMBO_IP:
1492                 {
1493                         DICT_ATTR const *da;
1494
1495                         if (inet_pton(AF_INET6, value, &vp->vp_ipv6addr) > 0) {
1496                                 da = dict_attrbytype(vp->da->attr, vp->da->vendor,
1497                                                      PW_TYPE_IPV6ADDR);
1498                                 if (!da) {
1499                                         fr_strerror_printf("Cannot find ipv6addr for %s", vp->da->name);
1500                                         return false;
1501                                 }
1502
1503                                 vp->length = 16; /* length of IPv6 address */
1504                         } else {
1505                                 fr_ipaddr_t ipaddr;
1506
1507                                 da = dict_attrbytype(vp->da->attr, vp->da->vendor,
1508                                                      PW_TYPE_IPADDR);
1509                                 if (!da) {
1510                                         fr_strerror_printf("Cannot find ipaddr for %s", vp->da->name);
1511                                         return false;
1512                                 }
1513
1514                                 if (ip_hton(value, AF_INET, &ipaddr) < 0) {
1515                                         fr_strerror_printf("Failed to find IPv4 address for %s", value);
1516                                         return false;
1517                                 }
1518
1519                                 vp->vp_ipaddr = ipaddr.ipaddr.ip4addr.s_addr;
1520                                 vp->length = 4;
1521                         }
1522
1523                         vp->da = da;
1524                 }
1525                 break;
1526
1527         case PW_TYPE_SIGNED: /* Damned code for 1 WiMAX attribute */
1528                 vp->vp_signed = (int32_t) strtol(value, &p, 10);
1529                 vp->length = 4;
1530                 break;
1531
1532         case PW_TYPE_TLV: /* don't use this! */
1533                 if (strncasecmp(value, "0x", 2) != 0) {
1534                         fr_strerror_printf("Invalid TLV specification");
1535                         return false;
1536                 }
1537                 length = strlen(value + 2) / 2;
1538                 if (vp->length < length) {
1539                         TALLOC_FREE(vp->vp_tlv);
1540                 }
1541                 vp->vp_tlv = talloc_array(vp, uint8_t, length);
1542                 if (!vp->vp_tlv) {
1543                         fr_strerror_printf("No memory");
1544                         return false;
1545                 }
1546                 if (fr_hex2bin(vp->vp_tlv, value + 2, length) != length) {
1547                         fr_strerror_printf("Invalid hex data in TLV");
1548                         return false;
1549                 }
1550                 vp->length = length;
1551                 break;
1552
1553                 /*
1554                  *  Anything else.
1555                  */
1556         default:
1557                 fr_strerror_printf("unknown attribute type %d", vp->da->type);
1558                 return false;
1559         }
1560
1561         finish:
1562         vp->type = VT_DATA;
1563         return true;
1564 }
1565
1566 /** Use simple heuristics to create an VALUE_PAIR from an unknown address string
1567  *
1568  * If a DICT_ATTR is not provided for the address type, parsing will fail with
1569  * and error.
1570  *
1571  * @param ctx to allocate VP in.
1572  * @param value IPv4/IPv6 address/prefix string.
1573  * @param ipv4 dictionary attribute to use for an IPv4 address.
1574  * @param ipv6 dictionary attribute to use for an IPv6 address.
1575  * @param ipv4_prefix dictionary attribute to use for an IPv4 prefix.
1576  * @param ipv6_prefix dictionary attribute to use for an IPv6 prefix.
1577  * @return NULL on error, or new VALUE_PAIR.
1578  */
1579 VALUE_PAIR *pairmake_ip(TALLOC_CTX *ctx, char const *value, DICT_ATTR *ipv4, DICT_ATTR *ipv6,
1580                         DICT_ATTR *ipv4_prefix, DICT_ATTR *ipv6_prefix)
1581 {
1582         VALUE_PAIR *vp;
1583         DICT_ATTR *da = NULL;
1584
1585         if (!fr_assert(ipv4 || ipv6 || ipv4_prefix || ipv6_prefix)) {
1586                 return NULL;
1587         }
1588
1589         /* No point in repeating the work of pairparsevalue */
1590         if (strchr(value, ':')) {
1591                 if (strchr(value, '/')) {
1592                         da = ipv6_prefix;
1593                         goto finish;
1594                 }
1595
1596                 da = ipv6;
1597                 goto finish;
1598         }
1599
1600         if (strchr(value, '/')) {
1601                 da = ipv4_prefix;
1602                 goto finish;
1603         }
1604
1605         if (ipv4) {
1606                 da = ipv4;
1607                 goto finish;
1608         }
1609
1610         fr_strerror_printf("Invalid IP value specified, allowed types are %s%s%s%s",
1611                            ipv4 ? "ipaddr " : "", ipv6 ? "ipv6addr " : "",
1612                            ipv4_prefix ? "ipv4prefix " : "", ipv6_prefix ? "ipv6prefix" : "");
1613
1614 finish:
1615         vp = pairalloc(ctx, da);
1616         if (!vp) return NULL;
1617         if (!pairparsevalue(vp, value)) {
1618                 talloc_free(vp);
1619                 return NULL;
1620         }
1621
1622         return vp;
1623 }
1624
1625 /** Create a valuepair from an ASCII attribute and value
1626  *
1627  * Where the attribute name is in the form:
1628  *  - Attr-%d
1629  *  - Attr-%d.%d.%d...
1630  *  - Vendor-%d-Attr-%d
1631  *  - VendorName-Attr-%d
1632  *
1633  * @param ctx for talloc
1634  * @param attribute name to parse.
1635  * @param value to parse (must be a hex string).
1636  * @param op to assign to new valuepair.
1637  * @return new valuepair or NULL on error.
1638  */
1639 static VALUE_PAIR *pairmake_any(TALLOC_CTX *ctx,
1640                                 char const *attribute, char const *value,
1641                                 FR_TOKEN op)
1642 {
1643         VALUE_PAIR      *vp;
1644         DICT_ATTR const *da;
1645
1646         uint8_t         *data;
1647         size_t          size;
1648
1649         da = dict_attrunknownbyname(attribute, true);
1650         if (!da) return NULL;
1651
1652         /*
1653          *      Unknown attributes MUST be of type 'octets'
1654          */
1655         if (value && (strncasecmp(value, "0x", 2) != 0)) {
1656                 fr_strerror_printf("Unknown attribute \"%s\" requires a hex "
1657                                    "string, not \"%s\"", attribute, value);
1658
1659                 dict_attr_free(&da);
1660                 return NULL;
1661         }
1662
1663         /*
1664          *      We've now parsed the attribute properly, Let's create
1665          *      it.  This next stop also looks the attribute up in the
1666          *      dictionary, and creates the appropriate type for it.
1667          */
1668         vp = pairalloc(ctx, da);
1669         if (!vp) {
1670                 dict_attr_free(&da);
1671                 return NULL;
1672         }
1673
1674         vp->op = (op == 0) ? T_OP_EQ : op;
1675
1676         if (!value) return vp;
1677
1678         size = strlen(value + 2);
1679         vp->length = size >> 1;
1680         data = talloc_array(vp, uint8_t, vp->length);
1681
1682         if (fr_hex2bin(data, value + 2, size) != vp->length) {
1683                 fr_strerror_printf("Invalid hex string");
1684                 talloc_free(vp);
1685                 return NULL;
1686         }
1687
1688         vp->vp_octets = data;
1689         vp->type = VT_DATA;
1690         return vp;
1691 }
1692
1693
1694 /** Create a VALUE_PAIR from ASCII strings
1695  *
1696  * Converts an attribute string identifier (with an optional tag qualifier)
1697  * and value string into a VALUE_PAIR.
1698  *
1699  * The string value is parsed according to the type of VALUE_PAIR being created.
1700  *
1701  * @param[in] ctx for talloc
1702  * @param[in] vps list where the attribute will be added (optional)
1703  * @param[in] attribute name.
1704  * @param[in] value attribute value (may be NULL if value will be set later).
1705  * @param[in] op to assign to new VALUE_PAIR.
1706  * @return a new VALUE_PAIR.
1707  */
1708 VALUE_PAIR *pairmake(TALLOC_CTX *ctx, VALUE_PAIR **vps,
1709                      char const *attribute, char const *value, FR_TOKEN op)
1710 {
1711         DICT_ATTR const *da;
1712         VALUE_PAIR      *vp;
1713         char            *tc, *ts;
1714         int8_t          tag;
1715         int             found_tag;
1716         char            buffer[256];
1717         char const      *attrname = attribute;
1718
1719         /*
1720          *    Check for tags in 'Attribute:Tag' format.
1721          */
1722         found_tag = 0;
1723         tag = 0;
1724
1725         ts = strrchr(attribute, ':');
1726         if (ts && !ts[1]) {
1727                 fr_strerror_printf("Invalid tag for attribute %s", attribute);
1728                 return NULL;
1729         }
1730
1731         if (ts && ts[1]) {
1732                 strlcpy(buffer, attribute, sizeof(buffer));
1733                 attrname = buffer;
1734                 ts = strrchr(attrname, ':');
1735                 if (!ts) return NULL;
1736
1737                  /* Colon found with something behind it */
1738                  if (ts[1] == '*' && ts[2] == 0) {
1739                          /* Wildcard tag for check items */
1740                          tag = TAG_ANY;
1741                          *ts = 0;
1742                  } else if ((ts[1] >= '0') && (ts[1] <= '9')) {
1743                          /* It's not a wild card tag */
1744                          tag = strtol(ts + 1, &tc, 0);
1745                          if (tc && !*tc && TAG_VALID_ZERO(tag))
1746                                  *ts = 0;
1747                          else tag = 0;
1748                  } else {
1749                          fr_strerror_printf("Invalid tag for attribute %s", attribute);
1750                          return NULL;
1751                  }
1752                  found_tag = 1;
1753         }
1754
1755         /*
1756          *      It's not found in the dictionary, so we use
1757          *      another method to create the attribute.
1758          */
1759         da = dict_attrbyname(attrname);
1760         if (!da) {
1761                 vp = pairmake_any(ctx, attrname, value, op);
1762                 if (vp && vps) pairadd(vps, vp);
1763                 return vp;
1764         }
1765
1766         /*      Check for a tag in the 'Merit' format of:
1767          *      :Tag:Value.  Print an error if we already found
1768          *      a tag in the Attribute.
1769          */
1770
1771         if (value && (*value == ':' && da->flags.has_tag)) {
1772                 /* If we already found a tag, this is invalid */
1773                 if(found_tag) {
1774                         fr_strerror_printf("Duplicate tag %s for attribute %s",
1775                                    value, da->name);
1776                         DEBUG("Duplicate tag %s for attribute %s\n",
1777                                    value, da->name);
1778                         return NULL;
1779                 }
1780                 /* Colon found and attribute allows a tag */
1781                 if (value[1] == '*' && value[2] == ':') {
1782                        /* Wildcard tag for check items */
1783                        tag = TAG_ANY;
1784                        value += 3;
1785                 } else {
1786                        /* Real tag */
1787                        tag = strtol(value + 1, &tc, 0);
1788                        if (tc && *tc==':' && TAG_VALID_ZERO(tag))
1789                             value = tc + 1;
1790                        else tag = 0;
1791                 }
1792         }
1793
1794         vp = pairalloc(ctx, da);
1795         if (!vp) return NULL;
1796         vp->op = (op == 0) ? T_OP_EQ : op;
1797         vp->tag = tag;
1798
1799         switch (vp->op) {
1800         default:
1801                 break;
1802
1803         case T_OP_CMP_TRUE:
1804         case T_OP_CMP_FALSE:
1805                 vp->vp_strvalue = NULL;
1806                 vp->length = 0;
1807                 value = NULL;   /* ignore it! */
1808                 break;
1809
1810                 /*
1811                  *      Regular expression comparison of integer attributes
1812                  *      does a STRING comparison of the names of their
1813                  *      integer attributes.
1814                  */
1815         case T_OP_REG_EQ:       /* =~ */
1816         case T_OP_REG_NE:       /* !~ */
1817 #ifndef WITH_REGEX
1818                 fr_strerror_printf("Regular expressions are not supported");
1819                 return NULL;
1820
1821 #else
1822
1823                 /*
1824                  *      Someone else will fill in the value.
1825                  */
1826                 if (!value) break;
1827
1828                 talloc_free(vp);
1829
1830                 if (1) {
1831                         int compare;
1832                         regex_t reg;
1833
1834                         compare = regcomp(&reg, value, REG_EXTENDED);
1835                         if (compare != 0) {
1836                                 regerror(compare, &reg, buffer, sizeof(buffer));
1837                                 fr_strerror_printf("Illegal regular expression in attribute: %s: %s",
1838                                            attribute, buffer);
1839                                 return NULL;
1840                         }
1841                 }
1842
1843                 vp = pairmake(ctx, NULL, attribute, NULL, op);
1844                 if (!vp) return NULL;
1845
1846                 if (pairmark_xlat(vp, value) < 0) {
1847                         talloc_free(vp);
1848                         return NULL;
1849                 }
1850
1851                 value = NULL;   /* ignore it */
1852                 break;
1853 #endif
1854         }
1855
1856         /*
1857          *      FIXME: if (strcasecmp(attribute, vp->da->name) != 0)
1858          *      then the user MAY have typed in the attribute name
1859          *      as Vendor-%d-Attr-%d, and the value MAY be octets.
1860          *
1861          *      We probably want to fix pairparsevalue to accept
1862          *      octets as values for any attribute.
1863          */
1864         if (value && !pairparsevalue(vp, value)) {
1865                 talloc_free(vp);
1866                 return NULL;
1867         }
1868
1869         if (vps) pairadd(vps, vp);
1870         return vp;
1871 }
1872
1873 /** Mark a valuepair for xlat expansion
1874  *
1875  * Copies xlat source (unprocessed) string to valuepair value,
1876  * and sets value type.
1877  *
1878  * @param vp to mark for expansion.
1879  * @param value to expand.
1880  * @return 0 if marking succeeded or -1 if vp already had a value, or OOM.
1881  */
1882 int pairmark_xlat(VALUE_PAIR *vp, char const *value)
1883 {
1884         char *raw;
1885
1886         /*
1887          *      valuepair should not already have a value.
1888          */
1889         if (vp->type != VT_NONE) {
1890                 return -1;
1891         }
1892
1893         raw = talloc_typed_strdup(vp, value);
1894         if (!raw) {
1895                 return -1;
1896         }
1897
1898         vp->type = VT_XLAT;
1899         vp->value.xlat = raw;
1900         vp->length = 0;
1901
1902         return 0;
1903 }
1904
1905 /** Read a single valuepair from a buffer, and advance the pointer
1906  *
1907  * Sets *eol to T_EOL if end of line was encountered.
1908  *
1909  * @param[in,out] ptr to read from and update.
1910  * @param[out] raw The struct to write the raw VALUE_PAIR to.
1911  * @return the last token read.
1912  */
1913 FR_TOKEN pairread(char const **ptr, VALUE_PAIR_RAW *raw)
1914 {
1915         char const      *p;
1916         char *q;
1917         FR_TOKEN        ret = T_OP_INVALID, next, quote;
1918         char            buf[8];
1919
1920         if (!ptr || !*ptr || !raw) {
1921                 fr_strerror_printf("Invalid arguments");
1922                 return T_OP_INVALID;
1923         }
1924
1925         /*
1926          *      Skip leading spaces
1927          */
1928         p = *ptr;
1929         while ((*p == ' ') || (*p == '\t')) p++;
1930
1931         if (!*p) {
1932                 fr_strerror_printf("No token read where we expected "
1933                                    "an attribute name");
1934                 return T_OP_INVALID;
1935         }
1936
1937         if (*p == '#') {
1938                 fr_strerror_printf("Read a comment instead of a token");
1939
1940                 return T_HASH;
1941         }
1942
1943         /*
1944          *      Try to get the attribute name.
1945          */
1946         q = raw->l_opand;
1947         *q = '\0';
1948         while (*p) {
1949                 uint8_t const *t = (uint8_t const *) p;
1950
1951                 if (q >= (raw->l_opand + sizeof(raw->l_opand))) {
1952                 too_long:
1953                         fr_strerror_printf("Attribute name too long");
1954                         return T_OP_INVALID;
1955                 }
1956
1957                 /*
1958                  *      Only ASCII is allowed, and only a subset of that.
1959                  */
1960                 if ((*t < 32) || (*t >= 128)) {
1961                 invalid:
1962                         fr_strerror_printf("Invalid attribute name");
1963                         return T_OP_INVALID;
1964                 }
1965
1966                 /*
1967                  *      This is arguably easier than trying to figure
1968                  *      out which operators come after the attribute
1969                  *      name.  Yes, our "lexer" is bad.
1970                  */
1971                 if (!dict_attr_allowed_chars[(int) *t]) {
1972                         break;
1973                 }
1974
1975                 *(q++) = *(p++);
1976         }
1977
1978         /*
1979          *      ASCII, but not a valid attribute name.
1980          */
1981         if (!*raw->l_opand) goto invalid;
1982
1983         /*
1984          *      Look for tag (:#).  This is different from :=, which
1985          *      is an operator.
1986          */
1987         if ((*p == ':') && (isdigit((int) p[1]))) {
1988                 if (q >= (raw->l_opand + sizeof(raw->l_opand))) {
1989                         goto too_long;
1990                 }
1991                 *(q++) = *(p++);
1992
1993                 while (isdigit((int) *p)) {
1994                         if (q >= (raw->l_opand + sizeof(raw->l_opand))) {
1995                                 goto too_long;
1996                         }
1997                         *(q++) = *(p++);
1998                 }
1999         }
2000
2001         *q = '\0';
2002         *ptr = p;
2003
2004         /* Now we should have an operator here. */
2005         raw->op = gettoken(ptr, buf, sizeof(buf));
2006         if (raw->op  < T_EQSTART || raw->op  > T_EQEND) {
2007                 fr_strerror_printf("Expecting operator");
2008
2009                 return T_OP_INVALID;
2010         }
2011
2012         /*
2013          *      Read value.  Note that empty string values are allowed
2014          */
2015         quote = gettoken(ptr, raw->r_opand, sizeof(raw->r_opand));
2016         if (quote == T_EOL) {
2017                 fr_strerror_printf("Failed to get value");
2018
2019                 return T_OP_INVALID;
2020         }
2021
2022         /*
2023          *      Peek at the next token. Must be T_EOL, T_COMMA, or T_HASH
2024          */
2025         p = *ptr;
2026
2027         next = gettoken(&p, buf, sizeof(buf));
2028         switch (next) {
2029         case T_EOL:
2030         case T_HASH:
2031                 break;
2032
2033         case T_COMMA:
2034                 *ptr = p;
2035                 break;
2036
2037         default:
2038                 fr_strerror_printf("Expected end of line or comma");
2039                 return T_OP_INVALID;
2040         }
2041         ret = next;
2042
2043         switch (quote) {
2044         /*
2045          *      Perhaps do xlat's
2046          */
2047         case T_DOUBLE_QUOTED_STRING:
2048                 /*
2049                  *      Only report as double quoted if it contained valid
2050                  *      a valid xlat expansion.
2051                  */
2052                 p = strchr(raw->r_opand, '%');
2053                 if (p && (p[1] == '{')) {
2054                         raw->quote = quote;
2055                 } else {
2056                         raw->quote = T_SINGLE_QUOTED_STRING;
2057                 }
2058
2059                 break;
2060         default:
2061                 raw->quote = quote;
2062
2063                 break;
2064         }
2065
2066         return ret;
2067 }
2068
2069 /** Read one line of attribute/value pairs into a list.
2070  *
2071  * The line may specify multiple attributes separated by commas.
2072  *
2073  * @note If the function returns T_OP_INVALID, an error has occurred and
2074  * @note the valuepair list should probably be freed.
2075  *
2076  * @param ctx for talloc
2077  * @param buffer to read valuepairs from.
2078  * @param list where the parsed VALUE_PAIRs will be appended.
2079  * @return the last token parsed, or T_OP_INVALID
2080  */
2081 FR_TOKEN userparse(TALLOC_CTX *ctx, char const *buffer, VALUE_PAIR **list)
2082 {
2083         VALUE_PAIR      *vp, *head, **tail;
2084         char const      *p;
2085         FR_TOKEN        last_token = T_OP_INVALID;
2086         FR_TOKEN        previous_token;
2087         VALUE_PAIR_RAW  raw;
2088
2089         /*
2090          *      We allow an empty line.
2091          */
2092         if (buffer[0] == 0) {
2093                 return T_EOL;
2094         }
2095
2096         head = NULL;
2097         tail = &head;
2098
2099         p = buffer;
2100         do {
2101                 raw.l_opand[0] = '\0';
2102                 raw.r_opand[0] = '\0';
2103
2104                 previous_token = last_token;
2105
2106                 last_token = pairread(&p, &raw);
2107                 if (last_token == T_OP_INVALID) break;
2108
2109                 if (raw.quote == T_DOUBLE_QUOTED_STRING) {
2110                         vp = pairmake(ctx, NULL, raw.l_opand, NULL, raw.op);
2111                         if (!vp) {
2112                                 last_token = T_OP_INVALID;
2113                                 break;
2114                         }
2115                         if (pairmark_xlat(vp, raw.r_opand) < 0) {
2116                                 talloc_free(vp);
2117                                 last_token = T_OP_INVALID;
2118                                 break;
2119                         }
2120                 } else {
2121                         vp = pairmake(ctx, NULL, raw.l_opand, raw.r_opand, raw.op);
2122                         if (!vp) {
2123                                 last_token = T_OP_INVALID;
2124                                 break;
2125                         }
2126                 }
2127
2128                 *tail = vp;
2129                 tail = &((*tail)->next);
2130         } while (*p && (last_token == T_COMMA));
2131
2132         /*
2133          *      Don't tell the caller that there was a comment.
2134          */
2135         if (last_token == T_HASH) {
2136                 last_token = previous_token;
2137         }
2138
2139         if (last_token == T_OP_INVALID) {
2140                 pairfree(&head);
2141         } else {
2142                 pairadd(list, head);
2143         }
2144
2145         /*
2146          *      And return the last token which we read.
2147          */
2148         return last_token;
2149 }
2150
2151 /*
2152  *      Read valuepairs from the fp up to End-Of-File.
2153  *
2154  *      Hmm... this function is only used by radclient..
2155  */
2156 VALUE_PAIR *readvp2(TALLOC_CTX *ctx, FILE *fp, bool *pfiledone, char const *errprefix)
2157 {
2158         char buf[8192];
2159         FR_TOKEN last_token = T_EOL;
2160         VALUE_PAIR *vp;
2161         VALUE_PAIR *list;
2162         bool error = false;
2163
2164         list = NULL;
2165
2166         while (!error && fgets(buf, sizeof(buf), fp) != NULL) {
2167                 /*
2168                  *      If we get a '\n' by itself, we assume that's
2169                  *      the end of that VP
2170                  */
2171                 if ((buf[0] == '\n') && (list)) {
2172                         return list;
2173                 }
2174                 if ((buf[0] == '\n') && (!list)) {
2175                         continue;
2176                 }
2177
2178                 /*
2179                  *      Comments get ignored
2180                  */
2181                 if (buf[0] == '#') continue;
2182
2183                 /*
2184                  *      Read all of the attributes on the current line.
2185                  */
2186                 vp = NULL;
2187                 last_token = userparse(ctx, buf, &vp);
2188                 if (!vp) {
2189                         if (last_token != T_EOL) {
2190                                 fr_perror("%s", errprefix);
2191                                 error = true;
2192                                 break;
2193                         }
2194                         break;
2195                 }
2196
2197                 pairadd(&list, vp);
2198                 buf[0] = '\0';
2199         }
2200
2201         if (error) pairfree(&list);
2202
2203         *pfiledone = true;
2204
2205         return list;
2206 }
2207
2208 /*
2209  *      We leverage the fact that IPv4 and IPv6 prefixes both
2210  *      have the same format:
2211  *
2212  *      reserved, prefix-len, data...
2213  */
2214 static int paircmp_cidr(FR_TOKEN op, int bytes, uint8_t const *one, uint8_t const *two)
2215 {
2216         int i, common;
2217         uint32_t mask;
2218
2219         /*
2220          *      Handle the case of netmasks being identical.
2221          */
2222         if (one[1] == two[1]) {
2223                 int compare;
2224
2225                 compare = memcmp(one + 2, two + 2, bytes);
2226
2227                 /*
2228                  *      If they're identical return true for
2229                  *      identical.
2230                  */
2231                 if ((compare == 0) &&
2232                     ((op == T_OP_CMP_EQ) ||
2233                      (op == T_OP_LE) ||
2234                      (op == T_OP_GE))) {
2235                         return true;
2236                 }
2237
2238                 /*
2239                  *      Everything else returns false.
2240                  *
2241                  *      10/8 == 24/8  --> false
2242                  *      10/8 <= 24/8  --> false
2243                  *      10/8 >= 24/8  --> false
2244                  */
2245                 return false;
2246         }
2247
2248         /*
2249          *      Netmasks are different.  That limits the
2250          *      possible results, based on the operator.
2251          */
2252         switch (op) {
2253         case T_OP_CMP_EQ:
2254                 return false;
2255
2256         case T_OP_NE:
2257                 return true;
2258
2259         case T_OP_LE:
2260         case T_OP_LT:   /* 192/8 < 192.168/16 --> false */
2261                 if (one[1] < two[1]) {
2262                         return false;
2263                 }
2264                 break;
2265
2266         case T_OP_GE:
2267         case T_OP_GT:   /* 192/16 > 192.168/8 --> false */
2268                 if (one[1] > two[1]) {
2269                         return false;
2270                 }
2271                 break;
2272
2273         default:
2274                 return false;
2275         }
2276
2277         if (one[1] < two[1]) {
2278                 common = one[1];
2279         } else {
2280                 common = two[1];
2281         }
2282
2283         /*
2284          *      Do the check byte by byte.  If the bytes are
2285          *      identical, it MAY be a match.  If they're different,
2286          *      it is NOT a match.
2287          */
2288         i = 2;
2289         while (i < (2 + bytes)) {
2290                 /*
2291                  *      All leading bytes are identical.
2292                  */
2293                 if (common == 0) return true;
2294
2295                 /*
2296                  *      Doing bitmasks takes more work.
2297                  */
2298                 if (common < 8) break;
2299
2300                 if (one[i] != two[i]) return false;
2301
2302                 common -= 8;
2303                 i++;
2304                 continue;
2305         }
2306
2307         mask = 1;
2308         mask <<= (8 - common);
2309         mask--;
2310         mask = ~mask;
2311
2312         if ((one[i] & mask) == ((two[i] & mask))) {
2313                 return true;
2314         }
2315
2316         return false;
2317 }
2318
2319 /*
2320  *      Compare two pairs, using the operator from "one".
2321  *
2322  *      i.e. given two attributes, it does:
2323  *
2324  *      (two->data) (one->operator) (one->data)
2325  *
2326  *      e.g. "foo" != "bar"
2327  *
2328  *      Returns true (comparison is true), or false (comparison is not true);
2329  */
2330 int paircmp(VALUE_PAIR *one, VALUE_PAIR *two)
2331 {
2332         int compare;
2333
2334         VERIFY_VP(one);
2335         VERIFY_VP(two);
2336
2337         switch (one->op) {
2338         case T_OP_CMP_TRUE:
2339                 return (two != NULL);
2340
2341         case T_OP_CMP_FALSE:
2342                 return (two == NULL);
2343
2344                 /*
2345                  *      One is a regex, compile it, print two to a string,
2346                  *      and then do string comparisons.
2347                  */
2348         case T_OP_REG_EQ:
2349         case T_OP_REG_NE:
2350 #ifndef WITH_REGEX
2351                 return -1;
2352 #else
2353                 {
2354                         regex_t reg;
2355                         char buffer[MAX_STRING_LEN * 4 + 1];
2356
2357                         compare = regcomp(&reg, one->vp_strvalue, REG_EXTENDED);
2358                         if (compare != 0) {
2359                                 regerror(compare, &reg, buffer, sizeof(buffer));
2360                                 fr_strerror_printf("Illegal regular expression in attribute: %s: %s",
2361                                            one->da->name, buffer);
2362                                 return -1;
2363                         }
2364
2365                         vp_prints_value(buffer, sizeof(buffer), two, 0);
2366
2367                         /*
2368                          *      Don't care about substring matches,
2369                          *      oh well...
2370                          */
2371                         compare = regexec(&reg, buffer, 0, NULL, 0);
2372
2373                         regfree(&reg);
2374                         if (one->op == T_OP_REG_EQ) return (compare == 0);
2375                         return (compare != 0);
2376                 }
2377 #endif
2378
2379         default:                /* we're OK */
2380                 break;
2381         }
2382
2383         return paircmp_op(two, one->op, one);
2384 }
2385
2386 /* Compare two attributes
2387  *
2388  * @param[in] one the first attribute
2389  * @param[in] op the operator for comparison
2390  * @param[in] two the second attribute
2391  * @return true (comparison is true), or false (comparison is not true);
2392  */
2393 int paircmp_op(VALUE_PAIR const *one, FR_TOKEN op, VALUE_PAIR const *two)
2394 {
2395         int compare = 0;
2396
2397         VERIFY_VP(one);
2398         VERIFY_VP(two);
2399
2400         /*
2401          *      Can't compare two attributes of differing types
2402          *
2403          *      FIXME: maybe do checks for IP OP IP/mask ??
2404          */
2405         if (one->da->type != two->da->type) {
2406                 return one->da->type - two->da->type;
2407         }
2408
2409         /*
2410          *      After doing the previous check for special comparisons,
2411          *      do the per-type comparison here.
2412          */
2413         switch (one->da->type) {
2414         case PW_TYPE_ABINARY:
2415         case PW_TYPE_OCTETS:
2416         {
2417                 size_t length;
2418
2419                 if (one->length > two->length) {
2420                         length = one->length;
2421                 } else {
2422                         length = two->length;
2423                 }
2424
2425                 if (length) {
2426                         compare = memcmp(one->vp_octets, two->vp_octets,
2427                                          length);
2428                         if (compare != 0) break;
2429                 }
2430
2431                 /*
2432                  *      Contents are the same.  The return code
2433                  *      is therefore the difference in lengths.
2434                  *
2435                  *      i.e. "0x00" is smaller than "0x0000"
2436                  */
2437                 compare = one->length - two->length;
2438         }
2439                 break;
2440
2441         case PW_TYPE_STRING:
2442                 compare = strcmp(one->vp_strvalue, two->vp_strvalue);
2443                 break;
2444
2445         case PW_TYPE_BYTE:
2446         case PW_TYPE_SHORT:
2447         case PW_TYPE_INTEGER:
2448         case PW_TYPE_DATE:
2449                 if (one->vp_integer < two->vp_integer) {
2450                         compare = -1;
2451                 } else if (one->vp_integer == two->vp_integer) {
2452                         compare = 0;
2453                 } else {
2454                         compare = +1;
2455                 }
2456                 break;
2457
2458         case PW_TYPE_SIGNED:
2459                 if (one->vp_signed < two->vp_signed) {
2460                         compare = -1;
2461                 } else if (one->vp_signed == two->vp_signed) {
2462                         compare = 0;
2463                 } else {
2464                         compare = +1;
2465                 }
2466                 break;
2467
2468         case PW_TYPE_INTEGER64:
2469                 /*
2470                  *      Don't want integer overflow!
2471                  */
2472                 if (one->vp_integer64 < two->vp_integer64) {
2473                         compare = -1;
2474                 } else if (one->vp_integer64 > two->vp_integer64) {
2475                         compare = +1;
2476                 } else {
2477                         compare = 0;
2478                 }
2479                 break;
2480
2481         case PW_TYPE_ETHERNET:
2482                 compare = memcmp(&one->vp_ether, &two->vp_ether,
2483                                  sizeof(one->vp_ether));
2484                 break;
2485
2486         case PW_TYPE_IPADDR:
2487                 if (ntohl(one->vp_ipaddr) < ntohl(two->vp_ipaddr)) {
2488                         compare = -1;
2489                 } else if (one->vp_ipaddr  == two->vp_ipaddr) {
2490                         compare = 0;
2491                 } else {
2492                         compare = +1;
2493                 }
2494                 break;
2495
2496         case PW_TYPE_IPV6ADDR:
2497                 compare = memcmp(&one->vp_ipv6addr, &two->vp_ipv6addr,
2498                                  sizeof(one->vp_ipv6addr));
2499                 break;
2500
2501         case PW_TYPE_IPV6PREFIX:
2502                 return paircmp_cidr(op, 16,
2503                                     (uint8_t const *) &one->vp_ipv6prefix,
2504                                     (uint8_t const *) &two->vp_ipv6prefix);
2505
2506         case PW_TYPE_IPV4PREFIX:
2507                 return paircmp_cidr(op, 4,
2508                                     (uint8_t const *) &one->vp_ipv4prefix,
2509                                     (uint8_t const *) &two->vp_ipv4prefix);
2510
2511         case PW_TYPE_IFID:
2512                 compare = memcmp(&one->vp_ifid, &two->vp_ifid, sizeof(one->vp_ifid));
2513                 break;
2514
2515         /*
2516          *      None of the types below should be in the REQUEST
2517          */
2518         case PW_TYPE_COMBO_IP:          /* This should of been converted into IPADDR/IPV6ADDR */
2519         case PW_TYPE_TLV:
2520         case PW_TYPE_EXTENDED:
2521         case PW_TYPE_LONG_EXTENDED:
2522         case PW_TYPE_EVS:
2523         case PW_TYPE_VSA:
2524         case PW_TYPE_INVALID:           /* We should never see these */
2525         case PW_TYPE_MAX:
2526                 fr_assert(0);   /* unknown type */
2527                 return 0;
2528
2529         /*
2530          *      Do NOT add a default here, as new types are added
2531          *      static analysis will warn us they're not handled
2532          */
2533         }
2534
2535         /*
2536          *      Now do the operator comparison.
2537          */
2538         switch (op) {
2539         case T_OP_CMP_EQ:
2540                 return (compare == 0);
2541
2542         case T_OP_NE:
2543                 return (compare != 0);
2544
2545         case T_OP_LT:
2546                 return (compare < 0);
2547
2548         case T_OP_GT:
2549                 return (compare > 0);
2550
2551         case T_OP_LE:
2552                 return (compare <= 0);
2553
2554         case T_OP_GE:
2555                 return (compare >= 0);
2556
2557         default:
2558                 return 0;
2559         }
2560 }
2561
2562 /** Set the type of the VALUE_PAIR value buffer to match it's DICT_ATTR
2563  *
2564  * @param vp to fixup.
2565  */
2566 void pairtypeset(VALUE_PAIR *vp)
2567 {
2568         if (!vp->data.ptr) return;
2569
2570         switch(vp->da->type) {
2571         case PW_TYPE_OCTETS:
2572         case PW_TYPE_TLV:
2573                 talloc_set_type(vp->data.ptr, uint8_t);
2574                 return;
2575
2576         case PW_TYPE_STRING:
2577                 talloc_set_type(vp->data.ptr, char);
2578                 return;
2579
2580         default:
2581                 return;
2582         }
2583 }
2584
2585 /** Copy data into an "octets" data type.
2586  *
2587  * @param[in,out] vp to update
2588  * @param[in] src data to copy
2589  * @param[in] size of the data
2590  */
2591 void pairmemcpy(VALUE_PAIR *vp, uint8_t const *src, size_t size)
2592 {
2593         uint8_t *p, *q;
2594
2595         VERIFY_VP(vp);
2596
2597         p = talloc_memdup(vp, src, size);
2598         if (!p) return;
2599         talloc_set_type(p, uint8_t);
2600
2601         memcpy(&q, &vp->vp_octets, sizeof(q));
2602         talloc_free(q);
2603
2604         vp->vp_octets = p;
2605         vp->length = size;
2606         pairtypeset(vp);
2607 }
2608
2609 /** Reparent an allocated octet buffer to a VALUE_PAIR
2610  *
2611  * @param[in,out] vp to update
2612  * @param[in] src buffer to steal.
2613  */
2614 void pairmemsteal(VALUE_PAIR *vp, uint8_t const *src)
2615 {
2616         uint8_t *q;
2617
2618         VERIFY_VP(vp);
2619
2620         memcpy(&q, &vp->vp_octets, sizeof(q));
2621         talloc_free(q);
2622
2623         vp->vp_octets = talloc_steal(vp, src);
2624         vp->type = VT_DATA;
2625         vp->length = talloc_array_length(vp->vp_octets);
2626         pairtypeset(vp);
2627 }
2628
2629 /** Reparent an allocated char buffer to a VALUE_PAIR
2630  *
2631  * @param[in,out] vp to update
2632  * @param[in] src buffer to steal.
2633  */
2634 void pairstrsteal(VALUE_PAIR *vp, char const *src)
2635 {
2636         uint8_t *q;
2637
2638         VERIFY_VP(vp);
2639
2640         memcpy(&q, &vp->vp_octets, sizeof(q));
2641         talloc_free(q);
2642
2643         vp->vp_strvalue = talloc_steal(vp, src);
2644         vp->type = VT_DATA;
2645         vp->length = talloc_array_length(vp->vp_strvalue) - 1;
2646         pairtypeset(vp);
2647 }
2648
2649 /** Copy data into an "string" data type.
2650  *
2651  * @param[in,out] vp to update
2652  * @param[in] src data to copy
2653  */
2654 void pairstrcpy(VALUE_PAIR *vp, char const *src)
2655 {
2656         char *p, *q;
2657
2658         VERIFY_VP(vp);
2659
2660         p = talloc_strdup(vp, src);
2661
2662         if (!p) return;
2663
2664         memcpy(&q, &vp->vp_strvalue, sizeof(q));
2665         talloc_free(q);
2666
2667         vp->vp_strvalue = p;
2668         vp->type = VT_DATA;
2669         vp->length = talloc_array_length(vp->vp_strvalue) - 1;
2670         pairtypeset(vp);
2671 }
2672
2673
2674 /** Print data into an "string" data type.
2675  *
2676  * @param[in,out] vp to update
2677  * @param[in] fmt the format string
2678  */
2679 void pairsprintf(VALUE_PAIR *vp, char const *fmt, ...)
2680 {
2681         va_list ap;
2682         char *p, *q;
2683
2684         VERIFY_VP(vp);
2685
2686         va_start(ap, fmt);
2687         p = talloc_vasprintf(vp, fmt, ap);
2688         va_end(ap);
2689
2690         if (!p) return;
2691
2692         memcpy(&q, &vp->vp_strvalue, sizeof(q));
2693         talloc_free(q);
2694
2695         vp->vp_strvalue = p;
2696         vp->type = VT_DATA;
2697
2698         vp->length = talloc_array_length(vp->vp_strvalue) - 1;
2699         pairtypeset(vp);
2700 }
2701