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