If error is set, list has been free'd, and is NULL
[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 || !*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, *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                          *      Anything else are operators which
977                          *      shouldn't occur.  We ignore them, and
978                          *      leave them in place.
979                          */
980                         default:
981                                 tail_from = &(i->next);
982                                 continue;
983
984                         /*
985                          *      Add it to the "to" list, but only if
986                          *      it doesn't already exist.
987                          */
988                         case T_OP_EQ:
989                                 found = pairfind(*to, i->da->attr, i->da->vendor,
990                                                  TAG_ANY);
991                                 if (!found) goto do_add;
992
993                                 tail_from = &(i->next);
994                                 continue;
995
996                         /*
997                          *      Add it to the "to" list, and delete any attribute
998                          *      of the same vendor/attr which already exists.
999                          */
1000                         case T_OP_SET:
1001                                 found = pairfind(*to, i->da->attr, i->da->vendor,
1002                                                  TAG_ANY);
1003                                 if (!found) goto do_add;
1004
1005                                 /*
1006                                  *      Do NOT call pairdelete() here,
1007                                  *      due to issues with re-writing
1008                                  *      "request->username".
1009                                  *
1010                                  *      Everybody calls pairmove, and
1011                                  *      expects it to work.  We can't
1012                                  *      update request->username here,
1013                                  *      so instead we over-write the
1014                                  *      vp that it's pointing to.
1015                                  */
1016                                 switch (found->da->type) {
1017                                         VALUE_PAIR *j;
1018
1019                                         default:
1020                                                 j = found->next;
1021                                                 memcpy(found, i, sizeof(*found));
1022                                                 found->next = j;
1023                                                 break;
1024
1025                                         case PW_TYPE_TLV:
1026                                                 pairmemsteal(found, i->vp_tlv);
1027                                                 i->vp_tlv = NULL;
1028                                                 break;
1029
1030                                         case PW_TYPE_OCTETS:
1031                                                 pairmemsteal(found, i->vp_octets);
1032                                                 i->vp_octets = NULL;
1033                                                 break;
1034
1035                                         case PW_TYPE_STRING:
1036                                                 pairstrsteal(found, i->vp_strvalue);
1037                                                 i->vp_strvalue = NULL;
1038                                                 found->tag = i->tag;
1039                                                 break;
1040                                 }
1041
1042                                 /*
1043                                  *      Delete *all* of the attributes
1044                                  *      of the same number.
1045                                  */
1046                                 pairdelete(&found->next,
1047                                            found->da->attr,
1048                                            found->da->vendor, TAG_ANY);
1049
1050                                 /*
1051                                  *      Remove this attribute from the
1052                                  *      "from" list.
1053                                  */
1054                                 *tail_from = i->next;
1055                                 i->next = NULL;
1056                                 pairfree(&i);
1057                                 continue;
1058
1059                         /*
1060                          *      Move it from the old list and add it
1061                          *      to the new list.
1062                          */
1063                         case T_OP_ADD:
1064                 do_add:
1065                                 *tail_from = i->next;
1066                                 i->next = NULL;
1067                                 *tail_new = talloc_steal(ctx, i);
1068                                 tail_new = &(i->next);
1069                                 continue;
1070                 }
1071         } /* loop over the "from" list. */
1072
1073         /*
1074          *      Take the "new" list, and append it to the "to" list.
1075          */
1076         pairadd(to, head_new);
1077 }
1078
1079 /** Move matching pairs between VALUE_PAIR lists
1080  *
1081  * Move pairs of a matching attribute number, vendor number and tag from the
1082  * the input list to the output list.
1083  *
1084  * @note pairfree should be called on the head of the old list to free unmoved
1085          attributes (if they're no longer needed).
1086  *
1087  * @param[in] ctx for talloc
1088  * @param[in,out] to destination list.
1089  * @param[in,out] from source list.
1090  * @param[in] attr to match, if PW_VENDOR_SPECIFIC and vendor 0, only VSAs will
1091  *            be copied.  If 0 and 0, all attributes will match
1092  * @param[in] vendor to match.
1093  * @param[in] tag to match, TAG_ANY matches any tag, TAG_UNUSED matches tagless VPs.
1094  */
1095 void pairfilter(TALLOC_CTX *ctx, VALUE_PAIR **to, VALUE_PAIR **from, unsigned int attr, unsigned int vendor, int8_t tag)
1096 {
1097         VALUE_PAIR *to_tail, *i, *next;
1098         VALUE_PAIR *iprev = NULL;
1099
1100         /*
1101          *      Find the last pair in the "to" list and put it in "to_tail".
1102          *
1103          *      @todo: replace the "if" with "VALUE_PAIR **tail"
1104          */
1105         if (*to != NULL) {
1106                 to_tail = *to;
1107                 for(i = *to; i; i = i->next) {
1108                         VERIFY_VP(i);
1109                         to_tail = i;
1110                 }
1111         } else
1112                 to_tail = NULL;
1113
1114         /*
1115          *      Attr/vendor of 0 means "move them all".
1116          *      It's better than "pairadd(foo,bar);bar=NULL"
1117          */
1118         if ((vendor == 0) && (attr == 0)) {
1119                 if (*to) {
1120                         to_tail->next = *from;
1121                 } else {
1122                         *to = *from;
1123                 }
1124
1125                 for (i = *from; i; i = i->next) {
1126                         (void) talloc_steal(ctx, i);
1127                 }
1128
1129                 *from = NULL;
1130                 return;
1131         }
1132
1133         for(i = *from; i; i = next) {
1134                 VERIFY_VP(i);
1135                 next = i->next;
1136
1137                 if ((tag != TAG_ANY) && i->da->flags.has_tag &&
1138                     (i->tag != tag)) {
1139                         continue;
1140                 }
1141
1142                 /*
1143                  *      vendor=0, attr = PW_VENDOR_SPECIFIC means
1144                  *      "match any vendor attribute".
1145                  */
1146                 if ((vendor == 0) && (attr == PW_VENDOR_SPECIFIC)) {
1147                         /*
1148                          *      It's a VSA: move it over.
1149                          */
1150                         if (i->da->vendor != 0) goto move;
1151
1152                         /*
1153                          *      It's Vendor-Specific: move it over.
1154                          */
1155                         if (i->da->attr == attr) goto move;
1156
1157                         /*
1158                          *      It's not a VSA: ignore it.
1159                          */
1160                         iprev = i;
1161                         continue;
1162                 }
1163
1164                 /*
1165                  *      If it isn't an exact match, ignore it.
1166                  */
1167                 if (!((i->da->vendor == vendor) && (i->da->attr == attr))) {
1168                         iprev = i;
1169                         continue;
1170                 }
1171
1172         move:
1173                 /*
1174                  *      Remove the attribute from the "from" list.
1175                  */
1176                 if (iprev)
1177                         iprev->next = next;
1178                 else
1179                         *from = next;
1180
1181                 /*
1182                  *      Add the attribute to the "to" list.
1183                  */
1184                 if (to_tail)
1185                         to_tail->next = i;
1186                 else
1187                         *to = i;
1188                 to_tail = i;
1189                 i->next = NULL;
1190                 (void) talloc_steal(ctx, i);
1191         }
1192 }
1193
1194 static char const *hextab = "0123456789abcdef";
1195
1196 bool pairparsevalue(VALUE_PAIR *vp, char const *value)
1197 {
1198         char            *p;
1199         char const      *cp, *cs;
1200         int             x;
1201         uint64_t        y;
1202         size_t          length;
1203         DICT_VALUE      *dval;
1204
1205         if (!value) return false;
1206         VERIFY_VP(vp);
1207
1208         /*
1209          *      It's a comparison, not a real VALUE_PAIR, copy the string over verbatim
1210          */
1211         if ((vp->op == T_OP_REG_EQ) || (vp->op == T_OP_REG_NE)) {
1212                 pairstrcpy(vp, value);  /* Icky hacky ewww */
1213                 goto finish;
1214         }
1215
1216         switch(vp->da->type) {
1217         case PW_TYPE_STRING:
1218                 /*
1219                  *      Do escaping here
1220                  */
1221                 p = talloc_strdup(vp, value);
1222                 vp->vp_strvalue = p;
1223                 cp = value;
1224                 length = 0;
1225
1226                 while (*cp) {
1227                         char c = *cp++;
1228
1229                         if (c == '\\') {
1230                                 switch (*cp) {
1231                                 case 'r':
1232                                         c = '\r';
1233                                         cp++;
1234                                         break;
1235                                 case 'n':
1236                                         c = '\n';
1237                                         cp++;
1238                                         break;
1239                                 case 't':
1240                                         c = '\t';
1241                                         cp++;
1242                                         break;
1243                                 case '"':
1244                                         c = '"';
1245                                         cp++;
1246                                         break;
1247                                 case '\'':
1248                                         c = '\'';
1249                                         cp++;
1250                                         break;
1251                                 case '\\':
1252                                         c = '\\';
1253                                         cp++;
1254                                         break;
1255                                 case '`':
1256                                         c = '`';
1257                                         cp++;
1258                                         break;
1259                                 case '\0':
1260                                         c = '\\'; /* no cp++ */
1261                                         break;
1262                                 default:
1263                                         if ((cp[0] >= '0') &&
1264                                             (cp[0] <= '9') &&
1265                                             (cp[1] >= '0') &&
1266                                             (cp[1] <= '9') &&
1267                                             (cp[2] >= '0') &&
1268                                             (cp[2] <= '9') &&
1269                                             (sscanf(cp, "%3o", &x) == 1)) {
1270                                                 c = x;
1271                                                 cp += 3;
1272                                         } /* else just do '\\' */
1273                                 }
1274                         }
1275                         *p++ = c;
1276                         length++;
1277                 }
1278                 *p = '\0';
1279                 vp->length = length;
1280                 break;
1281
1282         case PW_TYPE_IPADDR:
1283                 /*
1284                  *      FIXME: complain if hostname
1285                  *      cannot be resolved, or resolve later!
1286                  */
1287                 p = NULL;
1288                 {
1289                         fr_ipaddr_t ipaddr;
1290                         char ipv4[16];
1291
1292                         /*
1293                          *      Convert things which are obviously integers to IP addresses
1294                          *
1295                          *      We assume the number is the bigendian representation of the
1296                          *      IP address.
1297                          */
1298                         if (fr_integer_check(value)) {
1299                                 vp->vp_ipaddr = htonl(atol(value));
1300                                 break;
1301                         }
1302
1303                         /*
1304                          *      Certain applications/databases print IPv4 addresses with a
1305                          *      /32 suffix. Strip it off if the mask is 32, else error out.
1306                          */
1307                         p = strchr(value, '/');
1308                         if (p) {
1309                                 if ((p[1] != '3') || (p[2] != '2') || (p[3] != '\0')) {
1310                                         fr_strerror_printf("Invalid IP address suffix \"%s\".  Only '/32' permitted "
1311                                                            "for non-prefix types", p);
1312                                         return false;
1313                                 }
1314
1315                                 strlcpy(ipv4, value, sizeof(ipv4));
1316                                 ipv4[p - value] = '\0';
1317                                 cs = ipv4;
1318                         } else {
1319                                 cs = value;
1320                         }
1321
1322                         if (ip_hton(cs, AF_INET, &ipaddr) < 0) {
1323                                 fr_strerror_printf("Failed to find IP address for %s", cs);
1324                                 return false;
1325                         }
1326
1327                         vp->vp_ipaddr = ipaddr.ipaddr.ip4addr.s_addr;
1328                 }
1329                 vp->length = 4;
1330                 break;
1331
1332         case PW_TYPE_BYTE:
1333                 vp->length = 1;
1334
1335                 /*
1336                  *      Note that ALL integers are unsigned!
1337                  */
1338                 vp->vp_integer = fr_strtoul(value, &p);
1339                 if (!*p) {
1340                         if (vp->vp_integer > 255) {
1341                                 fr_strerror_printf("Byte value \"%s\" is larger than 255", value);
1342                                 return false;
1343                         }
1344                         break;
1345                 }
1346                 if (fr_whitespace_check(p)) break;
1347                 goto check_for_value;
1348
1349         case PW_TYPE_SHORT:
1350                 /*
1351                  *      Note that ALL integers are unsigned!
1352                  */
1353                 vp->vp_integer = fr_strtoul(value, &p);
1354                 vp->length = 2;
1355                 if (!*p) {
1356                         if (vp->vp_integer > 65535) {
1357                                 fr_strerror_printf("Byte value \"%s\" is larger than 65535", value);
1358                                 return false;
1359                         }
1360                         break;
1361                 }
1362                 if (fr_whitespace_check(p)) break;
1363                 goto check_for_value;
1364
1365         case PW_TYPE_INTEGER:
1366                 /*
1367                  *      Note that ALL integers are unsigned!
1368                  */
1369                 vp->vp_integer = fr_strtoul(value, &p);
1370                 vp->length = 4;
1371                 if (!*p) break;
1372                 if (fr_whitespace_check(p)) break;
1373
1374         check_for_value:
1375                 /*
1376                  *      Look for the named value for the given
1377                  *      attribute.
1378                  */
1379                 if ((dval = dict_valbyname(vp->da->attr, vp->da->vendor, value)) == NULL) {
1380                         fr_strerror_printf("Unknown value '%s' for attribute '%s'", value, vp->da->name);
1381                         return false;
1382                 }
1383                 vp->vp_integer = dval->value;
1384                 break;
1385
1386         case PW_TYPE_INTEGER64:
1387                 /*
1388                  *      Note that ALL integers are unsigned!
1389                  */
1390                 if (sscanf(value, "%" PRIu64, &y) != 1) {
1391                         fr_strerror_printf("Invalid value '%s' for attribute '%s'",
1392                                            value, vp->da->name);
1393                         return false;
1394                 }
1395                 vp->vp_integer64 = y;
1396                 vp->length = 8;
1397                 length = strspn(value, "0123456789");
1398                 if (fr_whitespace_check(value + length)) break;
1399                 break;
1400
1401         case PW_TYPE_DATE:
1402                 {
1403                         /*
1404                          *      time_t may be 64 bits, whule vp_date
1405                          *      MUST be 32-bits.  We need an
1406                          *      intermediary variable to handle
1407                          *      the conversions.
1408                          */
1409                         time_t date;
1410
1411                         if (fr_get_time(value, &date) < 0) {
1412                                 fr_strerror_printf("failed to parse time string "
1413                                            "\"%s\"", value);
1414                                 return false;
1415                         }
1416
1417                         vp->vp_date = date;
1418                 }
1419                 vp->length = 4;
1420                 break;
1421
1422         case PW_TYPE_ABINARY:
1423 #ifdef WITH_ASCEND_BINARY
1424                 if (strncasecmp(value, "0x", 2) == 0) {
1425                         goto do_octets;
1426                 }
1427
1428                 if (ascend_parse_filter(vp, value) < 0 ) {
1429                         /* Allow ascend_parse_filter's strerror to bubble up */
1430                         return false;
1431                 }
1432                 break;
1433
1434                 /*
1435                  *      If Ascend binary is NOT defined,
1436                  *      then fall through to raw octets, so that
1437                  *      the user can at least make them by hand...
1438                  */
1439 #endif
1440         /* raw octets: 0x01020304... */
1441         case PW_TYPE_VSA:
1442                 if (strcmp(value, "ANY") == 0) {
1443                         vp->length = 0;
1444                         break;
1445                 } /* else it's hex */
1446
1447         case PW_TYPE_OCTETS:
1448                 if (strncasecmp(value, "0x", 2) == 0) {
1449                         size_t size;
1450                         uint8_t *us;
1451
1452 #ifdef WITH_ASCEND_BINARY
1453                 do_octets:
1454 #endif
1455                         cp = value + 2;
1456                         size = strlen(cp);
1457                         vp->length = size >> 1;
1458                         us = talloc_array(vp, uint8_t, vp->length);
1459
1460                         /*
1461                          *      Invalid.
1462                          */
1463                         if ((size & 0x01) != 0) {
1464                                 fr_strerror_printf("Hex string is not an even length string");
1465                                 return false;
1466                         }
1467
1468                         if (fr_hex2bin(us, cp, vp->length) != vp->length) {
1469                                 fr_strerror_printf("Invalid hex data");
1470                                 return false;
1471                         }
1472                         vp->vp_octets = us;
1473                 } else {
1474                         pairstrcpy(vp, value);
1475                 }
1476                 break;
1477
1478         case PW_TYPE_IFID:
1479                 if (ifid_aton(value, (void *) &vp->vp_ifid) == NULL) {
1480                         fr_strerror_printf("Failed to parse interface-id string \"%s\"", value);
1481                         return false;
1482                 }
1483                 vp->length = 8;
1484                 break;
1485
1486         case PW_TYPE_IPV6ADDR:
1487                 {
1488                         fr_ipaddr_t ipaddr;
1489
1490                         if (ip_hton(value, AF_INET6, &ipaddr) < 0) {
1491                                 char buffer[1024];
1492
1493                                 strlcpy(buffer, fr_strerror(), sizeof(buffer));
1494
1495                                 fr_strerror_printf("failed to parse IPv6 address "
1496                                                    "string \"%s\": %s", value, buffer);
1497                                 return false;
1498                         }
1499                         vp->vp_ipv6addr = ipaddr.ipaddr.ip6addr;
1500                         vp->length = 16; /* length of IPv6 address */
1501                 }
1502                 break;
1503
1504         case PW_TYPE_IPV6PREFIX:
1505                 p = strchr(value, '/');
1506                 if (!p || ((p - value) >= 256)) {
1507                         fr_strerror_printf("invalid IPv6 prefix string \"%s\"", value);
1508                         return false;
1509                 } else {
1510                         unsigned int prefix;
1511                         char buffer[256], *eptr;
1512
1513                         memcpy(buffer, value, p - value);
1514                         buffer[p - value] = '\0';
1515
1516                         if (inet_pton(AF_INET6, buffer, vp->vp_ipv6prefix + 2) <= 0) {
1517                                 fr_strerror_printf("failed to parse IPv6 address string \"%s\"", value);
1518                                 return false;
1519                         }
1520
1521                         prefix = strtoul(p + 1, &eptr, 10);
1522                         if ((prefix > 128) || *eptr) {
1523                                 fr_strerror_printf("failed to parse IPv6 address string \"%s\"", value);
1524                                 return false;
1525                         }
1526                         vp->vp_ipv6prefix[1] = prefix;
1527
1528                         if (prefix < 128) {
1529                                 struct in6_addr addr;
1530
1531                                 addr = fr_ipaddr_mask6((struct in6_addr *)(&vp->vp_ipv6prefix[2]), prefix);
1532                                 memcpy(vp->vp_ipv6prefix + 2, &addr, sizeof(addr));
1533                         }
1534                 }
1535                 vp->length = 16 + 2;
1536                 break;
1537
1538         case PW_TYPE_IPV4PREFIX:
1539                 p = strchr(value, '/');
1540
1541                 /*
1542                  *      192.0.2.2 is parsed as if it was /32
1543                  */
1544                 if (!p) {
1545                         vp->vp_ipv4prefix[1] = 32;
1546
1547                         if (inet_pton(AF_INET, value, vp->vp_ipv4prefix + 2) <= 0) {
1548                                 fr_strerror_printf("failed to parse IPv4 address string \"%s\"", value);
1549                                 return false;
1550                         }
1551                         vp->length = sizeof(vp->vp_ipv4prefix);
1552                         break;
1553                 }
1554
1555                 /*
1556                  *      Otherwise parse the prefix
1557                  */
1558                 if ((p - value) >= 256) {
1559                         fr_strerror_printf("invalid IPv4 prefix string \"%s\"", value);
1560                         return false;
1561                 } else {
1562                         unsigned int prefix;
1563                         char buffer[256], *eptr;
1564
1565                         memcpy(buffer, value, p - value);
1566                         buffer[p - value] = '\0';
1567
1568                         if (inet_pton(AF_INET, buffer, vp->vp_ipv4prefix + 2) <= 0) {
1569                                 fr_strerror_printf("failed to parse IPv4 address string \"%s\"", value);
1570                                 return false;
1571                         }
1572
1573                         prefix = strtoul(p + 1, &eptr, 10);
1574                         if ((prefix > 32) || *eptr) {
1575                                 fr_strerror_printf("failed to parse IPv4 address string \"%s\"", value);
1576                                 return false;
1577                         }
1578                         vp->vp_ipv4prefix[1] = prefix;
1579
1580                         if (prefix < 32) {
1581                                 struct in_addr addr;
1582
1583                                 addr = fr_ipaddr_mask((struct in_addr *)(&vp->vp_ipv4prefix[2]), prefix);
1584                                 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
1585                         }
1586                 }
1587                 vp->length = sizeof(vp->vp_ipv4prefix);
1588                 break;
1589
1590         case PW_TYPE_ETHERNET:
1591                 {
1592                         char const *c1, *c2;
1593
1594                         /*
1595                          *      Convert things which are obviously integers to Ethernet addresses
1596                          *
1597                          *      We assume the number is the bigendian representation of the
1598                          *      ethernet address.
1599                          */
1600                         if (fr_integer_check(value)) {
1601                                 uint64_t integer = htonll(atoll(value));
1602
1603                                 memcpy(&vp->vp_ether, &integer, sizeof(vp->vp_ether));
1604                                 break;
1605                         }
1606
1607                         length = 0;
1608                         cp = value;
1609                         while (*cp) {
1610                                 if (cp[1] == ':') {
1611                                         c1 = hextab;
1612                                         c2 = memchr(hextab, tolower((int) cp[0]), 16);
1613                                         cp += 2;
1614                                 } else if ((cp[1] != '\0') &&
1615                                            ((cp[2] == ':') ||
1616                                             (cp[2] == '\0'))) {
1617                                            c1 = memchr(hextab, tolower((int) cp[0]), 16);
1618                                            c2 = memchr(hextab, tolower((int) cp[1]), 16);
1619                                            cp += 2;
1620                                            if (*cp == ':') cp++;
1621                                 } else {
1622                                         c1 = c2 = NULL;
1623                                 }
1624                                 if (!c1 || !c2 || (length >= sizeof(vp->vp_ether))) {
1625                                         fr_strerror_printf("failed to parse Ethernet address \"%s\"", value);
1626                                         return false;
1627                                 }
1628                                 vp->vp_ether[length] = ((c1-hextab)<<4) + (c2-hextab);
1629                                 length++;
1630                         }
1631                 }
1632                 vp->length = 6;
1633                 break;
1634
1635         /*
1636          *      Crazy polymorphic (IPv4/IPv6) attribute type for WiMAX.
1637          *
1638          *      We try and make is saner by replacing the original
1639          *      da, with either an IPv4 or IPv6 da type.
1640          *
1641          *      These are not dynamic da, and will have the same vendor
1642          *      and attribute as the original.
1643          */
1644         case PW_TYPE_COMBO_IP:
1645                 {
1646                         DICT_ATTR const *da;
1647
1648                         if (inet_pton(AF_INET6, value, &vp->vp_ipv6addr) > 0) {
1649                                 da = dict_attrbytype(vp->da->attr, vp->da->vendor,
1650                                                      PW_TYPE_IPV6ADDR);
1651                                 if (!da) {
1652                                         fr_strerror_printf("Cannot find ipv6addr for %s", vp->da->name);
1653                                         return false;
1654                                 }
1655
1656                                 vp->length = 16; /* length of IPv6 address */
1657                         } else {
1658                                 fr_ipaddr_t ipaddr;
1659
1660                                 da = dict_attrbytype(vp->da->attr, vp->da->vendor,
1661                                                      PW_TYPE_IPADDR);
1662                                 if (!da) {
1663                                         fr_strerror_printf("Cannot find ipaddr for %s", vp->da->name);
1664                                         return false;
1665                                 }
1666
1667                                 if (ip_hton(value, AF_INET, &ipaddr) < 0) {
1668                                         fr_strerror_printf("Failed to find IPv4 address for %s", value);
1669                                         return false;
1670                                 }
1671
1672                                 vp->vp_ipaddr = ipaddr.ipaddr.ip4addr.s_addr;
1673                                 vp->length = 4;
1674                         }
1675
1676                         vp->da = da;
1677                 }
1678                 break;
1679
1680         case PW_TYPE_SIGNED: /* Damned code for 1 WiMAX attribute */
1681                 vp->vp_signed = (int32_t) strtol(value, &p, 10);
1682                 vp->length = 4;
1683                 break;
1684
1685         case PW_TYPE_TLV: /* don't use this! */
1686                 if (strncasecmp(value, "0x", 2) != 0) {
1687                         fr_strerror_printf("Invalid TLV specification");
1688                         return false;
1689                 }
1690                 length = strlen(value + 2) / 2;
1691                 if (vp->length < length) {
1692                         TALLOC_FREE(vp->vp_tlv);
1693                 }
1694                 vp->vp_tlv = talloc_array(vp, uint8_t, length);
1695                 if (!vp->vp_tlv) {
1696                         fr_strerror_printf("No memory");
1697                         return false;
1698                 }
1699                 if (fr_hex2bin(vp->vp_tlv, value + 2, length) != length) {
1700                         fr_strerror_printf("Invalid hex data in TLV");
1701                         return false;
1702                 }
1703                 vp->length = length;
1704                 break;
1705
1706                 /*
1707                  *  Anything else.
1708                  */
1709         default:
1710                 fr_strerror_printf("unknown attribute type %d", vp->da->type);
1711                 return false;
1712         }
1713
1714         finish:
1715         vp->type = VT_DATA;
1716         return true;
1717 }
1718
1719 /** Create a valuepair from an ASCII attribute and value
1720  *
1721  * Where the attribute name is in the form:
1722  *  - Attr-%d
1723  *  - Attr-%d.%d.%d...
1724  *  - Vendor-%d-Attr-%d
1725  *  - VendorName-Attr-%d
1726  *
1727  * @param ctx for talloc
1728  * @param attribute name to parse.
1729  * @param value to parse (must be a hex string).
1730  * @param op to assign to new valuepair.
1731  * @return new valuepair or NULL on error.
1732  */
1733 static VALUE_PAIR *pairmake_any(TALLOC_CTX *ctx,
1734                                 char const *attribute, char const *value,
1735                                 FR_TOKEN op)
1736 {
1737         VALUE_PAIR      *vp;
1738         DICT_ATTR const *da;
1739
1740         uint8_t         *data;
1741         size_t          size;
1742
1743         da = dict_attrunknownbyname(attribute, true);
1744         if (!da) return NULL;
1745
1746         /*
1747          *      Unknown attributes MUST be of type 'octets'
1748          */
1749         if (value && (strncasecmp(value, "0x", 2) != 0)) {
1750                 fr_strerror_printf("Unknown attribute \"%s\" requires a hex "
1751                                    "string, not \"%s\"", attribute, value);
1752
1753                 dict_attr_free(&da);
1754                 return NULL;
1755         }
1756
1757         /*
1758          *      We've now parsed the attribute properly, Let's create
1759          *      it.  This next stop also looks the attribute up in the
1760          *      dictionary, and creates the appropriate type for it.
1761          */
1762         vp = pairalloc(ctx, da);
1763         if (!vp) {
1764                 dict_attr_free(&da);
1765                 return NULL;
1766         }
1767
1768         vp->op = (op == 0) ? T_OP_EQ : op;
1769
1770         if (!value) return vp;
1771
1772         size = strlen(value + 2);
1773         vp->length = size >> 1;
1774         data = talloc_array(vp, uint8_t, vp->length);
1775
1776         if (fr_hex2bin(data, value + 2, size) != vp->length) {
1777                 fr_strerror_printf("Invalid hex string");
1778                 talloc_free(vp);
1779                 return NULL;
1780         }
1781
1782         vp->vp_octets = data;
1783         vp->type = VT_DATA;
1784         return vp;
1785 }
1786
1787
1788 /** Create a VALUE_PAIR from ASCII strings
1789  *
1790  * Converts an attribute string identifier (with an optional tag qualifier)
1791  * and value string into a VALUE_PAIR.
1792  *
1793  * The string value is parsed according to the type of VALUE_PAIR being created.
1794  *
1795  * @param[in] ctx for talloc
1796  * @param[in] vps list where the attribute will be added (optional)
1797  * @param[in] attribute name.
1798  * @param[in] value attribute value (may be NULL if value will be set later).
1799  * @param[in] op to assign to new VALUE_PAIR.
1800  * @return a new VALUE_PAIR.
1801  */
1802 VALUE_PAIR *pairmake(TALLOC_CTX *ctx, VALUE_PAIR **vps,
1803                      char const *attribute, char const *value, FR_TOKEN op)
1804 {
1805         DICT_ATTR const *da;
1806         VALUE_PAIR      *vp;
1807         char            *tc, *ts;
1808         int8_t          tag;
1809         int             found_tag;
1810         char            buffer[256];
1811         char const      *attrname = attribute;
1812
1813         /*
1814          *    Check for tags in 'Attribute:Tag' format.
1815          */
1816         found_tag = 0;
1817         tag = 0;
1818
1819         ts = strrchr(attribute, ':');
1820         if (ts && !ts[1]) {
1821                 fr_strerror_printf("Invalid tag for attribute %s", attribute);
1822                 return NULL;
1823         }
1824
1825         if (ts && ts[1]) {
1826                 strlcpy(buffer, attribute, sizeof(buffer));
1827                 attrname = buffer;
1828                 ts = strrchr(attrname, ':');
1829                 if (!ts) return NULL;
1830
1831                  /* Colon found with something behind it */
1832                  if (ts[1] == '*' && ts[2] == 0) {
1833                          /* Wildcard tag for check items */
1834                          tag = TAG_ANY;
1835                          *ts = 0;
1836                  } else if ((ts[1] >= '0') && (ts[1] <= '9')) {
1837                          /* It's not a wild card tag */
1838                          tag = strtol(ts + 1, &tc, 0);
1839                          if (tc && !*tc && TAG_VALID_ZERO(tag))
1840                                  *ts = 0;
1841                          else tag = 0;
1842                  } else {
1843                          fr_strerror_printf("Invalid tag for attribute %s", attribute);
1844                          return NULL;
1845                  }
1846                  found_tag = 1;
1847         }
1848
1849         /*
1850          *      It's not found in the dictionary, so we use
1851          *      another method to create the attribute.
1852          */
1853         da = dict_attrbyname(attrname);
1854         if (!da) {
1855                 vp = pairmake_any(ctx, attrname, value, op);
1856                 if (vp && vps) pairadd(vps, vp);
1857                 return vp;
1858         }
1859
1860         /*      Check for a tag in the 'Merit' format of:
1861          *      :Tag:Value.  Print an error if we already found
1862          *      a tag in the Attribute.
1863          */
1864
1865         if (value && (*value == ':' && da->flags.has_tag)) {
1866                 /* If we already found a tag, this is invalid */
1867                 if(found_tag) {
1868                         fr_strerror_printf("Duplicate tag %s for attribute %s",
1869                                    value, da->name);
1870                         DEBUG("Duplicate tag %s for attribute %s\n",
1871                                    value, da->name);
1872                         return NULL;
1873                 }
1874                 /* Colon found and attribute allows a tag */
1875                 if (value[1] == '*' && value[2] == ':') {
1876                        /* Wildcard tag for check items */
1877                        tag = TAG_ANY;
1878                        value += 3;
1879                 } else {
1880                        /* Real tag */
1881                        tag = strtol(value + 1, &tc, 0);
1882                        if (tc && *tc==':' && TAG_VALID_ZERO(tag))
1883                             value = tc + 1;
1884                        else tag = 0;
1885                 }
1886         }
1887
1888         vp = pairalloc(ctx, da);
1889         if (!vp) {
1890                 return NULL;
1891         }
1892
1893         vp->op = (op == 0) ? T_OP_EQ : op;
1894         vp->tag = tag;
1895
1896         switch (vp->op) {
1897         default:
1898                 break;
1899
1900         case T_OP_CMP_TRUE:
1901         case T_OP_CMP_FALSE:
1902                 vp->vp_strvalue = NULL;
1903                 vp->length = 0;
1904                 value = NULL;   /* ignore it! */
1905                 break;
1906
1907                 /*
1908                  *      Regular expression comparison of integer attributes
1909                  *      does a STRING comparison of the names of their
1910                  *      integer attributes.
1911                  */
1912         case T_OP_REG_EQ:       /* =~ */
1913         case T_OP_REG_NE:       /* !~ */
1914 #ifndef WITH_REGEX
1915                 fr_strerror_printf("Regular expressions are not supported");
1916                 return NULL;
1917
1918 #else
1919
1920                 /*
1921                  *      Someone else will fill in the value.
1922                  */
1923                 if (!value) break;
1924
1925                 talloc_free(vp);
1926
1927                 if (1) {
1928                         int compare;
1929                         regex_t reg;
1930
1931                         compare = regcomp(&reg, value, REG_EXTENDED);
1932                         if (compare != 0) {
1933                                 regerror(compare, &reg, buffer, sizeof(buffer));
1934                                 fr_strerror_printf("Illegal regular expression in attribute: %s: %s",
1935                                            attribute, buffer);
1936                                 return NULL;
1937                         }
1938                 }
1939
1940                 vp = pairmake(ctx, NULL, attribute, NULL, op);
1941                 if (!vp) return NULL;
1942
1943                 if (pairmark_xlat(vp, value) < 0) {
1944                         talloc_free(vp);
1945                         return NULL;
1946                 }
1947
1948                 value = NULL;   /* ignore it */
1949                 break;
1950 #endif
1951         }
1952
1953         /*
1954          *      FIXME: if (strcasecmp(attribute, vp->da->name) != 0)
1955          *      then the user MAY have typed in the attribute name
1956          *      as Vendor-%d-Attr-%d, and the value MAY be octets.
1957          *
1958          *      We probably want to fix pairparsevalue to accept
1959          *      octets as values for any attribute.
1960          */
1961         if (value && !pairparsevalue(vp, value)) {
1962                 talloc_free(vp);
1963                 return NULL;
1964         }
1965
1966         if (vps) pairadd(vps, vp);
1967         return vp;
1968 }
1969
1970 /** Mark a valuepair for xlat expansion
1971  *
1972  * Copies xlat source (unprocessed) string to valuepair value,
1973  * and sets value type.
1974  *
1975  * @param vp to mark for expansion.
1976  * @param value to expand.
1977  * @return 0 if marking succeeded or -1 if vp already had a value, or OOM.
1978  */
1979 int pairmark_xlat(VALUE_PAIR *vp, char const *value)
1980 {
1981         char *raw;
1982
1983         /*
1984          *      valuepair should not already have a value.
1985          */
1986         if (vp->type != VT_NONE) {
1987                 return -1;
1988         }
1989
1990         raw = talloc_strdup(vp, value);
1991         if (!raw) {
1992                 return -1;
1993         }
1994
1995         vp->type = VT_XLAT;
1996         vp->value.xlat = raw;
1997         vp->length = 0;
1998
1999         return 0;
2000 }
2001
2002 /** Read a single valuepair from a buffer, and advance the pointer
2003  *
2004  * Sets *eol to T_EOL if end of line was encountered.
2005  *
2006  * @param[in,out] ptr to read from and update.
2007  * @param[out] raw The struct to write the raw VALUE_PAIR to.
2008  * @return the last token read.
2009  */
2010 FR_TOKEN pairread(char const **ptr, VALUE_PAIR_RAW *raw)
2011 {
2012         char const      *p;
2013         char *q;
2014         FR_TOKEN        ret = T_OP_INVALID, next, quote;
2015         char            buf[8];
2016
2017         if (!ptr || !*ptr || !raw) {
2018                 fr_strerror_printf("Invalid arguments");
2019                 return T_OP_INVALID;
2020         }
2021
2022         /*
2023          *      Skip leading spaces
2024          */
2025         p = *ptr;
2026         while ((*p == ' ') || (*p == '\t')) p++;
2027
2028         if (!*p) {
2029                 fr_strerror_printf("No token read where we expected "
2030                                    "an attribute name");
2031                 return T_OP_INVALID;
2032         }
2033
2034         if (*p == '#') {
2035                 fr_strerror_printf("Read a comment instead of a token");
2036
2037                 return T_HASH;
2038         }
2039
2040         /*
2041          *      Try to get the attribute name.
2042          */
2043         q = raw->l_opand;
2044         *q = '\0';
2045         while (*p) {
2046                 uint8_t const *t = (uint8_t const *) p;
2047
2048                 if (q >= (raw->l_opand + sizeof(raw->l_opand))) {
2049                 too_long:
2050                         fr_strerror_printf("Attribute name too long");
2051                         return T_OP_INVALID;
2052                 }
2053
2054                 /*
2055                  *      Only ASCII is allowed, and only a subset of that.
2056                  */
2057                 if ((*t < 32) || (*t >= 128)) {
2058                 invalid:
2059                         fr_strerror_printf("Invalid attribute name");
2060                         return T_OP_INVALID;
2061                 }
2062
2063                 /*
2064                  *      This is arguably easier than trying to figure
2065                  *      out which operators come after the attribute
2066                  *      name.  Yes, our "lexer" is bad.
2067                  */
2068                 if (!dict_attr_allowed_chars[(int) *t]) {
2069                         break;
2070                 }
2071
2072                 *(q++) = *(p++);
2073         }
2074
2075         /*
2076          *      ASCII, but not a valid attribute name.
2077          */
2078         if (!*raw->l_opand) goto invalid;
2079
2080         /*
2081          *      Look for tag (:#).  This is different from :=, which
2082          *      is an operator.
2083          */
2084         if ((*p == ':') && (isdigit((int) p[1]))) {
2085                 if (q >= (raw->l_opand + sizeof(raw->l_opand))) {
2086                         goto too_long;
2087                 }
2088                 *(q++) = *(p++);
2089
2090                 while (isdigit((int) *p)) {
2091                         if (q >= (raw->l_opand + sizeof(raw->l_opand))) {
2092                                 goto too_long;
2093                         }
2094                         *(q++) = *(p++);
2095                 }
2096         }
2097
2098         *q = '\0';
2099         *ptr = p;
2100
2101         /* Now we should have an operator here. */
2102         raw->op = gettoken(ptr, buf, sizeof(buf));
2103         if (raw->op  < T_EQSTART || raw->op  > T_EQEND) {
2104                 fr_strerror_printf("Expecting operator");
2105
2106                 return T_OP_INVALID;
2107         }
2108
2109         /*
2110          *      Read value.  Note that empty string values are allowed
2111          */
2112         quote = gettoken(ptr, raw->r_opand, sizeof(raw->r_opand));
2113         if (quote == T_EOL) {
2114                 fr_strerror_printf("Failed to get value");
2115
2116                 return T_OP_INVALID;
2117         }
2118
2119         /*
2120          *      Peek at the next token. Must be T_EOL, T_COMMA, or T_HASH
2121          */
2122         p = *ptr;
2123
2124         next = gettoken(&p, buf, sizeof(buf));
2125         switch (next) {
2126         case T_EOL:
2127         case T_HASH:
2128                 break;
2129
2130         case T_COMMA:
2131                 *ptr = p;
2132                 break;
2133
2134         default:
2135                 fr_strerror_printf("Expected end of line or comma");
2136                 return T_OP_INVALID;
2137         }
2138         ret = next;
2139
2140         switch (quote) {
2141         /*
2142          *      Perhaps do xlat's
2143          */
2144         case T_DOUBLE_QUOTED_STRING:
2145                 /*
2146                  *      Only report as double quoted if it contained valid
2147                  *      a valid xlat expansion.
2148                  */
2149                 p = strchr(raw->r_opand, '%');
2150                 if (p && (p[1] == '{')) {
2151                         raw->quote = quote;
2152                 } else {
2153                         raw->quote = T_SINGLE_QUOTED_STRING;
2154                 }
2155
2156                 break;
2157         default:
2158                 raw->quote = quote;
2159
2160                 break;
2161         }
2162
2163         return ret;
2164 }
2165
2166 /** Read one line of attribute/value pairs into a list.
2167  *
2168  * The line may specify multiple attributes separated by commas.
2169  *
2170  * @note If the function returns T_OP_INVALID, an error has occurred and
2171  * @note the valuepair list should probably be freed.
2172  *
2173  * @param ctx for talloc
2174  * @param buffer to read valuepairs from.
2175  * @param list where the parsed VALUE_PAIRs will be appended.
2176  * @return the last token parsed, or T_OP_INVALID
2177  */
2178 FR_TOKEN userparse(TALLOC_CTX *ctx, char const *buffer, VALUE_PAIR **list)
2179 {
2180         VALUE_PAIR      *vp, *head, **tail;
2181         char const      *p;
2182         FR_TOKEN        last_token = T_OP_INVALID;
2183         FR_TOKEN        previous_token;
2184         VALUE_PAIR_RAW  raw;
2185
2186         /*
2187          *      We allow an empty line.
2188          */
2189         if (buffer[0] == 0) {
2190                 return T_EOL;
2191         }
2192
2193         head = NULL;
2194         tail = &head;
2195
2196         p = buffer;
2197         do {
2198                 raw.l_opand[0] = '\0';
2199                 raw.r_opand[0] = '\0';
2200
2201                 previous_token = last_token;
2202
2203                 last_token = pairread(&p, &raw);
2204                 if (last_token == T_OP_INVALID) break;
2205
2206                 if (raw.quote == T_DOUBLE_QUOTED_STRING) {
2207                         vp = pairmake(ctx, NULL, raw.l_opand, NULL, raw.op);
2208                         if (!vp) {
2209                                 last_token = T_OP_INVALID;
2210                                 break;
2211                         }
2212                         if (pairmark_xlat(vp, raw.r_opand) < 0) {
2213                                 talloc_free(vp);
2214                                 last_token = T_OP_INVALID;
2215                                 break;
2216                         }
2217                 } else {
2218                         vp = pairmake(ctx, NULL, raw.l_opand, raw.r_opand, raw.op);
2219                         if (!vp) {
2220                                 last_token = T_OP_INVALID;
2221                                 break;
2222                         }
2223                 }
2224
2225                 *tail = vp;
2226                 tail = &((*tail)->next);
2227         } while (*p && (last_token == T_COMMA));
2228
2229         /*
2230          *      Don't tell the caller that there was a comment.
2231          */
2232         if (last_token == T_HASH) {
2233                 last_token = previous_token;
2234         }
2235
2236         if (last_token == T_OP_INVALID) {
2237                 pairfree(&head);
2238         } else {
2239                 pairadd(list, head);
2240         }
2241
2242         /*
2243          *      And return the last token which we read.
2244          */
2245         return last_token;
2246 }
2247
2248 /*
2249  *      Read valuepairs from the fp up to End-Of-File.
2250  *
2251  *      Hmm... this function is only used by radclient..
2252  */
2253 VALUE_PAIR *readvp2(TALLOC_CTX *ctx, FILE *fp, bool *pfiledone, char const *errprefix)
2254 {
2255         char buf[8192];
2256         FR_TOKEN last_token = T_EOL;
2257         VALUE_PAIR *vp;
2258         VALUE_PAIR *list;
2259         bool error = false;
2260
2261         list = NULL;
2262
2263         while (!error && fgets(buf, sizeof(buf), fp) != NULL) {
2264                 /*
2265                  *      If we get a '\n' by itself, we assume that's
2266                  *      the end of that VP
2267                  */
2268                 if ((buf[0] == '\n') && (list)) {
2269                         return list;
2270                 }
2271                 if ((buf[0] == '\n') && (!list)) {
2272                         continue;
2273                 }
2274
2275                 /*
2276                  *      Comments get ignored
2277                  */
2278                 if (buf[0] == '#') continue;
2279
2280                 /*
2281                  *      Read all of the attributes on the current line.
2282                  */
2283                 vp = NULL;
2284                 last_token = userparse(ctx, buf, &vp);
2285                 if (!vp) {
2286                         if (last_token != T_EOL) {
2287                                 fr_perror("%s", errprefix);
2288                                 error = false;
2289                                 break;
2290                         }
2291                         break;
2292                 }
2293
2294                 pairadd(&list, vp);
2295                 buf[0] = '\0';
2296         }
2297
2298         if (error) pairfree(&list);
2299
2300         *pfiledone = true;
2301
2302         return list;
2303 }
2304
2305 /*
2306  *      We leverage the fact that IPv4 and IPv6 prefixes both
2307  *      have the same format:
2308  *
2309  *      reserved, prefix-len, data...
2310  */
2311 static int paircmp_cidr(FR_TOKEN op, int bytes, uint8_t const *one, uint8_t const *two)
2312 {
2313         int i, common;
2314         uint32_t mask;
2315
2316         /*
2317          *      Handle the case of netmasks being identical.
2318          */
2319         if (one[1] == two[1]) {
2320                 int compare;
2321
2322                 compare = memcmp(one + 2, two + 2, bytes);
2323
2324                 /*
2325                  *      If they're identical return true for
2326                  *      identical.
2327                  */
2328                 if ((compare == 0) &&
2329                     ((op == T_OP_CMP_EQ) ||
2330                      (op == T_OP_LE) ||
2331                      (op == T_OP_GE))) {
2332                         return true;
2333                 }
2334
2335                 /*
2336                  *      Everything else returns false.
2337                  *
2338                  *      10/8 == 24/8  --> false
2339                  *      10/8 <= 24/8  --> false
2340                  *      10/8 >= 24/8  --> false
2341                  */
2342                 return false;
2343         }
2344
2345         /*
2346          *      Netmasks are different.  That limits the
2347          *      possible results, based on the operator.
2348          */
2349         switch (op) {
2350         case T_OP_CMP_EQ:
2351                 return false;
2352
2353         case T_OP_NE:
2354                 return true;
2355
2356         case T_OP_LE:
2357         case T_OP_LT:   /* 192/8 < 192.168/16 --> false */
2358                 if (one[1] < two[1]) {
2359                         return false;
2360                 }
2361                 break;
2362
2363         case T_OP_GE:
2364         case T_OP_GT:   /* 192/16 > 192.168/8 --> false */
2365                 if (one[1] > two[1]) {
2366                         return false;
2367                 }
2368                 break;
2369
2370         default:
2371                 return false;
2372         }
2373
2374         if (one[1] < two[1]) {
2375                 common = one[1];
2376         } else {
2377                 common = two[1];
2378         }
2379
2380         /*
2381          *      Do the check byte by byte.  If the bytes are
2382          *      identical, it MAY be a match.  If they're different,
2383          *      it is NOT a match.
2384          */
2385         i = 2;
2386         while (i < (2 + bytes)) {
2387                 /*
2388                  *      All leading bytes are identical.
2389                  */
2390                 if (common == 0) return true;
2391
2392                 /*
2393                  *      Doing bitmasks takes more work.
2394                  */
2395                 if (common < 8) break;
2396
2397                 if (one[i] != two[i]) return false;
2398
2399                 common -= 8;
2400                 i++;
2401                 continue;
2402         }
2403
2404         mask = 1;
2405         mask <<= (8 - common);
2406         mask--;
2407         mask = ~mask;
2408
2409         if ((one[i] & mask) == ((two[i] & mask))) {
2410                 return true;
2411         }
2412
2413         return false;
2414 }
2415
2416 /*
2417  *      Compare two pairs, using the operator from "one".
2418  *
2419  *      i.e. given two attributes, it does:
2420  *
2421  *      (two->data) (one->operator) (one->data)
2422  *
2423  *      e.g. "foo" != "bar"
2424  *
2425  *      Returns true (comparison is true), or false (comparison is not true);
2426  */
2427 int paircmp(VALUE_PAIR *one, VALUE_PAIR *two)
2428 {
2429         int compare;
2430
2431         VERIFY_VP(one);
2432         VERIFY_VP(two);
2433
2434         switch (one->op) {
2435         case T_OP_CMP_TRUE:
2436                 return (two != NULL);
2437
2438         case T_OP_CMP_FALSE:
2439                 return (two == NULL);
2440
2441                 /*
2442                  *      One is a regex, compile it, print two to a string,
2443                  *      and then do string comparisons.
2444                  */
2445         case T_OP_REG_EQ:
2446         case T_OP_REG_NE:
2447 #ifndef WITH_REGEX
2448                 return -1;
2449 #else
2450                 {
2451                         regex_t reg;
2452                         char buffer[MAX_STRING_LEN * 4 + 1];
2453
2454                         compare = regcomp(&reg, one->vp_strvalue, REG_EXTENDED);
2455                         if (compare != 0) {
2456                                 regerror(compare, &reg, buffer, sizeof(buffer));
2457                                 fr_strerror_printf("Illegal regular expression in attribute: %s: %s",
2458                                            one->da->name, buffer);
2459                                 return -1;
2460                         }
2461
2462                         vp_prints_value(buffer, sizeof(buffer), two, 0);
2463
2464                         /*
2465                          *      Don't care about substring matches,
2466                          *      oh well...
2467                          */
2468                         compare = regexec(&reg, buffer, 0, NULL, 0);
2469
2470                         regfree(&reg);
2471                         if (one->op == T_OP_REG_EQ) return (compare == 0);
2472                         return (compare != 0);
2473                 }
2474 #endif
2475
2476         default:                /* we're OK */
2477                 break;
2478         }
2479
2480         return paircmp_op(two, one->op, one);
2481 }
2482
2483 /* Compare two attributes
2484  *
2485  * @param[in] one the first attribute
2486  * @param[in] op the operator for comparison
2487  * @param[in] two the second attribute
2488  * @return < 0 if one is less than two, 0 if both are equal, > 0 if one is more than two.
2489  */
2490 int paircmp_op(VALUE_PAIR const *one, FR_TOKEN op, VALUE_PAIR const *two)
2491 {
2492         int compare;
2493
2494         VERIFY_VP(one);
2495         VERIFY_VP(two);
2496
2497         /*
2498          *      Can't compare two attributes of differing types
2499          *
2500          *      FIXME: maybe do checks for IP OP IP/mask ??
2501          */
2502         if (one->da->type != two->da->type) {
2503                 return one->da->type - two->da->type;
2504         }
2505
2506         /*
2507          *      After doing the previous check for special comparisons,
2508          *      do the per-type comparison here.
2509          */
2510         switch (one->da->type) {
2511         case PW_TYPE_ABINARY:
2512         case PW_TYPE_OCTETS:
2513         {
2514                 size_t length;
2515
2516                 if (one->length > two->length) {
2517                         length = one->length;
2518                 } else {
2519                         length = two->length;
2520                 }
2521
2522                 if (length) {
2523                         compare = memcmp(one->vp_octets, two->vp_octets,
2524                                          length);
2525                         if (compare != 0) break;
2526                 }
2527
2528                 /*
2529                  *      Contents are the same.  The return code
2530                  *      is therefore the difference in lengths.
2531                  *
2532                  *      i.e. "0x00" is smaller than "0x0000"
2533                  */
2534                 compare = one->length - two->length;
2535         }
2536                 break;
2537
2538         case PW_TYPE_STRING:
2539                 compare = strcmp(one->vp_strvalue, two->vp_strvalue);
2540                 break;
2541
2542         case PW_TYPE_BYTE:
2543         case PW_TYPE_SHORT:
2544         case PW_TYPE_INTEGER:
2545         case PW_TYPE_DATE:
2546                 if (one->vp_integer < two->vp_integer) {
2547                         compare = -1;
2548                 } else if (one->vp_integer == two->vp_integer) {
2549                         compare = 0;
2550                 } else {
2551                         compare = +1;
2552                 }
2553                 break;
2554
2555         case PW_TYPE_SIGNED:
2556                 if (one->vp_signed < two->vp_signed) {
2557                         compare = -1;
2558                 } else if (one->vp_signed == two->vp_signed) {
2559                         compare = 0;
2560                 } else {
2561                         compare = +1;
2562                 }
2563                 break;
2564
2565         case PW_TYPE_INTEGER64:
2566                 /*
2567                  *      Don't want integer overflow!
2568                  */
2569                 if (one->vp_integer64 < two->vp_integer64) {
2570                         compare = -1;
2571                 } else if (one->vp_integer64 > two->vp_integer64) {
2572                         compare = +1;
2573                 } else {
2574                         compare = 0;
2575                 }
2576                 break;
2577
2578         case PW_TYPE_ETHERNET:
2579                 compare = memcmp(&one->vp_ether, &two->vp_ether,
2580                                  sizeof(one->vp_ether));
2581                 break;
2582
2583         case PW_TYPE_IPADDR:
2584                 if (ntohl(one->vp_ipaddr) < ntohl(two->vp_ipaddr)) {
2585                         compare = -1;
2586                 } else if (one->vp_ipaddr  == two->vp_ipaddr) {
2587                         compare = 0;
2588                 } else {
2589                         compare = +1;
2590                 }
2591                 break;
2592
2593         case PW_TYPE_IPV6ADDR:
2594                 compare = memcmp(&one->vp_ipv6addr, &two->vp_ipv6addr,
2595                                  sizeof(one->vp_ipv6addr));
2596                 break;
2597
2598         case PW_TYPE_IPV6PREFIX:
2599                 return paircmp_cidr(op, 16,
2600                                     (uint8_t const *) &one->vp_ipv6prefix,
2601                                     (uint8_t const *) &two->vp_ipv6prefix);
2602
2603         case PW_TYPE_IPV4PREFIX:
2604                 return paircmp_cidr(op, 4,
2605                                     (uint8_t const *) &one->vp_ipv4prefix,
2606                                     (uint8_t const *) &two->vp_ipv4prefix);
2607
2608         case PW_TYPE_IFID:
2609                 compare = memcmp(&one->vp_ifid, &two->vp_ifid, sizeof(one->vp_ifid));
2610                 break;
2611
2612         /*
2613          *      None of the types below should be in the REQUEST
2614          */
2615         case PW_TYPE_COMBO_IP:          /* This should of been converted into IPADDR/IPV6ADDR */
2616         case PW_TYPE_TLV:
2617         case PW_TYPE_EXTENDED:
2618         case PW_TYPE_LONG_EXTENDED:
2619         case PW_TYPE_EVS:
2620         case PW_TYPE_VSA:
2621         case PW_TYPE_INVALID:           /* We should never see these */
2622         case PW_TYPE_MAX:
2623                 fr_assert(0);   /* unknown type */
2624                 return 0;
2625
2626         /*
2627          *      Do NOT add a default here, as new types are added
2628          *      static analysis will warn us they're not handled
2629          */
2630         }
2631
2632         /*
2633          *      Now do the operator comparison.
2634          */
2635         switch (op) {
2636         case T_OP_CMP_EQ:
2637                 return (compare == 0);
2638
2639         case T_OP_NE:
2640                 return (compare != 0);
2641
2642         case T_OP_LT:
2643                 return (compare < 0);
2644
2645         case T_OP_GT:
2646                 return (compare > 0);
2647
2648         case T_OP_LE:
2649                 return (compare <= 0);
2650
2651         case T_OP_GE:
2652                 return (compare >= 0);
2653
2654         default:
2655                 return 0;
2656         }
2657 }
2658
2659 /** Copy data into an "octets" data type.
2660  *
2661  * @param[in,out] vp to update
2662  * @param[in] src data to copy
2663  * @param[in] size of the data
2664  */
2665 void pairmemcpy(VALUE_PAIR *vp, uint8_t const *src, size_t size)
2666 {
2667         uint8_t *p, *q;
2668
2669         VERIFY_VP(vp);
2670
2671         p = talloc_memdup(vp, src, size);
2672         if (!p) return;
2673
2674         memcpy(&q, &vp->vp_octets, sizeof(q));
2675         talloc_free(q);
2676
2677         vp->vp_octets = p;
2678         vp->length = size;
2679 }
2680
2681 /** Reparent an allocated octet buffer to a VALUE_PAIR
2682  *
2683  * @param[in,out] vp to update
2684  * @param[in] src buffer to steal.
2685  */
2686 void pairmemsteal(VALUE_PAIR *vp, uint8_t const *src)
2687 {
2688         uint8_t *q;
2689         VERIFY_VP(vp);
2690
2691         memcpy(&q, &vp->vp_octets, sizeof(q));
2692         talloc_free(q);
2693
2694         vp->vp_octets = talloc_steal(vp, src);
2695         vp->type = VT_DATA;
2696         vp->length = talloc_array_length(vp->vp_octets);
2697 }
2698
2699 /** Reparent an allocated char buffer to a VALUE_PAIR
2700  *
2701  * @param[in,out] vp to update
2702  * @param[in] src buffer to steal.
2703  */
2704 void pairstrsteal(VALUE_PAIR *vp, char const *src)
2705 {
2706         uint8_t *q;
2707         VERIFY_VP(vp);
2708
2709         memcpy(&q, &vp->vp_octets, sizeof(q));
2710         talloc_free(q);
2711
2712         vp->vp_strvalue = talloc_steal(vp, src);
2713         vp->type = VT_DATA;
2714         vp->length = talloc_array_length(vp->vp_strvalue) - 1;
2715 }
2716
2717 /** Copy data into an "string" data type.
2718  *
2719  * @param[in,out] vp to update
2720  * @param[in] src data to copy
2721  */
2722 void pairstrcpy(VALUE_PAIR *vp, char const *src)
2723 {
2724         char *p, *q;
2725
2726         VERIFY_VP(vp);
2727
2728         p = talloc_strdup(vp, src);
2729         if (!p) return;
2730
2731         memcpy(&q, &vp->vp_strvalue, sizeof(q));
2732         talloc_free(q);
2733
2734         vp->vp_strvalue = p;
2735         vp->type = VT_DATA;
2736         vp->length = talloc_array_length(vp->vp_strvalue) - 1;
2737 }
2738
2739
2740 /** Print data into an "string" data type.
2741  *
2742  * @param[in,out] vp to update
2743  * @param[in] fmt the format string
2744  */
2745 void pairsprintf(VALUE_PAIR *vp, char const *fmt, ...)
2746 {
2747         va_list ap;
2748         char *p, *q;
2749
2750         VERIFY_VP(vp);
2751
2752         va_start(ap, fmt);
2753         p = talloc_vasprintf(vp, fmt, ap);
2754         va_end(ap);
2755
2756         if (!p) return;
2757
2758         memcpy(&q, &vp->vp_strvalue, sizeof(q));
2759         talloc_free(q);
2760
2761         vp->vp_strvalue = p;
2762         vp->type = VT_DATA;
2763
2764         vp->length = talloc_array_length(vp->vp_strvalue) - 1;
2765 }
2766