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