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