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