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