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