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