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