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