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