Allow %} as an expansion for a literal } Closes #1209
[freeradius.git] / src / main / xlat.c
1 /*
2  *   This program is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License as published by
4  *   the Free Software Foundation; either version 2 of the License, or
5  *   (at your option) any later version.
6  *
7  *   This program is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *   GNU General Public License for more details.
11  *
12  *   You should have received a copy of the GNU General Public License
13  *   along with this program; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16
17 /**
18  * $Id$
19  *
20  * @file xlat.c
21  * @brief String expansion ("translation"). Implements %Attribute -> value
22  *
23  * @copyright 2000,2006  The FreeRADIUS server project
24  * @copyright 2000  Alan DeKok <aland@ox.org>
25  */
26
27 RCSID("$Id$")
28
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/parser.h>
31 #include <freeradius-devel/rad_assert.h>
32 #include <freeradius-devel/base64.h>
33
34 #include <ctype.h>
35
36 typedef struct xlat_t {
37         char                    name[MAX_STRING_LEN];   //!< Name of the xlat expansion.
38         int                     length;                 //!< Length of name.
39         void                    *instance;              //!< Module instance passed to xlat and escape functions.
40         xlat_func_t             func;                   //!< xlat function.
41         xlat_escape_t   escape;                 //!< Escape function to apply to dynamic input to func.
42         bool                    internal;               //!< If true, cannot be redefined.
43 } xlat_t;
44
45 typedef enum {
46         XLAT_LITERAL,           //!< Literal string
47         XLAT_PERCENT,           //!< Literal string with %v
48         XLAT_MODULE,            //!< xlat module
49         XLAT_VIRTUAL,           //!< virtual attribute
50         XLAT_ATTRIBUTE,         //!< xlat attribute
51 #ifdef HAVE_REGEX
52         XLAT_REGEX,             //!< regex reference
53 #endif
54         XLAT_ALTERNATE          //!< xlat conditional syntax :-
55 } xlat_state_t;
56
57 struct xlat_exp {
58         char const *fmt;        //!< The format string.
59         size_t len;             //!< Length of the format string.
60
61         xlat_state_t type;      //!< type of this expansion.
62         xlat_exp_t *next;       //!< Next in the list.
63
64         xlat_exp_t *child;      //!< Nested expansion.
65         xlat_exp_t *alternate;  //!< Alternative expansion if this one expanded to a zero length string.
66
67         vp_tmpl_t attr; //!< An attribute template.
68         xlat_t const *xlat;     //!< The xlat expansion to expand format with.
69 };
70
71 typedef struct xlat_out {
72         char const *out;        //!< Output data.
73         size_t len;             //!< Length of the output string.
74 } xlat_out_t;
75
76 static rbtree_t *xlat_root = NULL;
77
78 #ifdef WITH_UNLANG
79 static char const * const xlat_foreach_names[] = {"Foreach-Variable-0",
80                                                   "Foreach-Variable-1",
81                                                   "Foreach-Variable-2",
82                                                   "Foreach-Variable-3",
83                                                   "Foreach-Variable-4",
84                                                   "Foreach-Variable-5",
85                                                   "Foreach-Variable-6",
86                                                   "Foreach-Variable-7",
87                                                   "Foreach-Variable-8",
88                                                   "Foreach-Variable-9",
89                                                   NULL};
90 #endif
91
92
93 static int xlat_inst[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };      /* up to 10 for foreach */
94
95 /** Print length of its RHS.
96  *
97  */
98 static ssize_t xlat_strlen(UNUSED void *instance, UNUSED REQUEST *request,
99                            char const *fmt, char *out, size_t outlen)
100 {
101         snprintf(out, outlen, "%u", (unsigned int) strlen(fmt));
102         return strlen(out);
103 }
104
105 /** Print the size of the attribute in bytes.
106  *
107  */
108 static ssize_t xlat_length(UNUSED void *instance, REQUEST *request,
109                            char const *fmt, char *out, size_t outlen)
110 {
111         VALUE_PAIR *vp;
112         while (isspace((int) *fmt)) fmt++;
113
114         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
115                 *out = '\0';
116                 return 0;
117         }
118
119         snprintf(out, outlen, "%zu", vp->vp_length);
120         return strlen(out);
121 }
122
123 /** Print data as integer, not as VALUE.
124  *
125  */
126 static ssize_t xlat_integer(UNUSED void *instance, REQUEST *request,
127                             char const *fmt, char *out, size_t outlen)
128 {
129         VALUE_PAIR      *vp;
130
131         uint64_t        int64 = 0;      /* Needs to be initialised to zero */
132         uint32_t        int32 = 0;      /* Needs to be initialised to zero */
133
134         while (isspace((int) *fmt)) fmt++;
135
136         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
137                 *out = '\0';
138                 return 0;
139         }
140
141         switch (vp->da->type) {
142         case PW_TYPE_OCTETS:
143         case PW_TYPE_STRING:
144                 if (vp->vp_length > 8) {
145                         break;
146                 }
147
148                 if (vp->vp_length > 4) {
149                         memcpy(&int64, vp->vp_octets, vp->vp_length);
150                         return snprintf(out, outlen, "%" PRIu64, htonll(int64));
151                 }
152
153                 memcpy(&int32, vp->vp_octets, vp->vp_length);
154                 return snprintf(out, outlen, "%i", htonl(int32));
155
156         case PW_TYPE_INTEGER64:
157                 return snprintf(out, outlen, "%" PRIu64, vp->vp_integer64);
158
159         /*
160          *      IP addresses are treated specially, as parsing functions assume the value
161          *      is bigendian and will convert it for us.
162          */
163         case PW_TYPE_IPV4_ADDR:
164                 return snprintf(out, outlen, "%u", htonl(vp->vp_ipaddr));
165
166         case PW_TYPE_IPV4_PREFIX:
167                 return snprintf(out, outlen, "%u", htonl((*(uint32_t *)(vp->vp_ipv4prefix + 2))));
168
169         case PW_TYPE_INTEGER:
170                 return snprintf(out, outlen, "%u", vp->vp_integer);
171
172         case PW_TYPE_DATE:
173                 return snprintf(out, outlen, "%u", vp->vp_date);
174
175         case PW_TYPE_BYTE:
176                 return snprintf(out, outlen, "%u", (unsigned int) vp->vp_byte);
177
178         case PW_TYPE_SHORT:
179                 return snprintf(out, outlen, "%u", (unsigned int) vp->vp_short);
180
181         /*
182          *      Ethernet is weird... It's network related, so we assume to it should be
183          *      bigendian.
184          */
185         case PW_TYPE_ETHERNET:
186                 memcpy(&int64, vp->vp_ether, vp->vp_length);
187                 return snprintf(out, outlen, "%" PRIu64, htonll(int64));
188
189         case PW_TYPE_SIGNED:
190                 return snprintf(out, outlen, "%i", vp->vp_signed);
191
192         case PW_TYPE_IPV6_ADDR:
193                 return fr_prints_uint128(out, outlen, ntohlll(*(uint128_t const *) &vp->vp_ipv6addr));
194
195         case PW_TYPE_IPV6_PREFIX:
196                 return fr_prints_uint128(out, outlen, ntohlll(*(uint128_t const *) &vp->vp_ipv6prefix[2]));
197
198         default:
199                 break;
200         }
201
202         REDEBUG("Type '%s' of length %zu cannot be converted to integer",
203                 fr_int2str(dict_attr_types, vp->da->type, "???"), vp->vp_length);
204         *out = '\0';
205
206         return -1;
207 }
208
209 /** Print data as hex, not as VALUE.
210  *
211  */
212 static ssize_t xlat_hex(UNUSED void *instance, REQUEST *request,
213                         char const *fmt, char *out, size_t outlen)
214 {
215         size_t i;
216         VALUE_PAIR *vp;
217         uint8_t const *p;
218         ssize_t ret;
219         size_t  len;
220         value_data_t dst;
221         uint8_t const *buff = NULL;
222
223         while (isspace((int) *fmt)) fmt++;
224
225         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
226         error:
227                 *out = '\0';
228                 return -1;
229         }
230
231         /*
232          *      The easy case.
233          */
234         if (vp->da->type == PW_TYPE_OCTETS) {
235                 p = vp->vp_octets;
236                 len = vp->vp_length;
237         /*
238          *      Cast the value_data_t of the VP to an octets string and
239          *      print that as hex.
240          */
241         } else {
242                 ret = value_data_cast(request, &dst, PW_TYPE_OCTETS, NULL, vp->da->type,
243                                       NULL, &vp->data, vp->vp_length);
244                 if (ret < 0) {
245                         REDEBUG("%s", fr_strerror());
246                         goto error;
247                 }
248                 len = (size_t) ret;
249                 p = buff = dst.octets;
250         }
251
252         rad_assert(p);
253
254         /*
255          *      Don't truncate the data.
256          */
257         if (outlen < (len * 2)) {
258                 rad_const_free(buff);
259                 goto error;
260         }
261
262         for (i = 0; i < len; i++) {
263                 snprintf(out + 2*i, 3, "%02x", p[i]);
264         }
265         rad_const_free(buff);
266
267         return len * 2;
268 }
269
270 /** Return the tag of an attribute reference
271  *
272  */
273 static ssize_t xlat_tag(UNUSED void *instance, REQUEST *request,
274                         char const *fmt, char *out, size_t outlen)
275 {
276         VALUE_PAIR *vp;
277
278         while (isspace((int) *fmt)) fmt++;
279
280         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
281                 *out = '\0';
282                 return 0;
283         }
284
285         if (!vp->da->flags.has_tag || !TAG_VALID(vp->tag)) {
286                 *out = '\0';
287                 return 0;
288         }
289
290         return snprintf(out, outlen, "%u", vp->tag);
291 }
292
293 /** Return the vendor of an attribute reference
294  *
295  */
296 static ssize_t xlat_vendor(UNUSED void *instance, REQUEST *request,
297                            char const *fmt, char *out, size_t outlen)
298 {
299         VALUE_PAIR *vp;
300         DICT_VENDOR *vendor;
301
302         while (isspace((int) *fmt)) fmt++;
303
304         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
305                 *out = '\0';
306                 return 0;
307         }
308
309         vendor = dict_vendorbyvalue(vp->da->vendor);
310         if (!vendor) {
311                 *out = '\0';
312                 return 0;
313         }
314         strlcpy(out, vendor->name, outlen);
315
316         return vendor->length;
317 }
318
319 /** Return the vendor number of an attribute reference
320  *
321  */
322 static ssize_t xlat_vendor_num(UNUSED void *instance, REQUEST *request,
323                                char const *fmt, char *out, size_t outlen)
324 {
325         VALUE_PAIR *vp;
326
327         while (isspace((int) *fmt)) fmt++;
328
329         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
330                 *out = '\0';
331                 return 0;
332         }
333
334         return snprintf(out, outlen, "%u", vp->da->vendor);
335 }
336
337 /** Return the attribute name of an attribute reference
338  *
339  */
340 static ssize_t xlat_attr(UNUSED void *instance, REQUEST *request,
341                          char const *fmt, char *out, size_t outlen)
342 {
343         VALUE_PAIR *vp;
344
345         while (isspace((int) *fmt)) fmt++;
346
347         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
348                 *out = '\0';
349                 return 0;
350         }
351         strlcpy(out, vp->da->name, outlen);
352
353         return strlen(vp->da->name);
354 }
355
356 /** Return the attribute number of an attribute reference
357  *
358  */
359 static ssize_t xlat_attr_num(UNUSED void *instance, REQUEST *request,
360                              char const *fmt, char *out, size_t outlen)
361 {
362         VALUE_PAIR *vp;
363
364         while (isspace((int) *fmt)) fmt++;
365
366         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
367                 *out = '\0';
368                 return 0;
369         }
370
371         return snprintf(out, outlen, "%u", vp->da->attr);
372 }
373
374 /** Print out attribute info
375  *
376  * Prints out all instances of a current attribute, or all attributes in a list.
377  *
378  * At higher debugging levels, also prints out alternative decodings of the same
379  * value. This is helpful to determine types for unknown attributes of long
380  * passed vendors, or just crazy/broken NAS.
381  *
382  * This expands to a zero length string.
383  */
384 static ssize_t xlat_debug_attr(UNUSED void *instance, REQUEST *request, char const *fmt,
385                                char *out, UNUSED size_t outlen)
386 {
387         VALUE_PAIR *vp;
388         vp_cursor_t cursor;
389
390         vp_tmpl_t vpt;
391
392         if (!RDEBUG_ENABLED2) {
393                 *out = '\0';
394                 return -1;
395         }
396
397         while (isspace((int) *fmt)) fmt++;
398
399         if (tmpl_from_attr_str(&vpt, fmt, REQUEST_CURRENT, PAIR_LIST_REQUEST, false, false) <= 0) {
400                 RDEBUG("%s", fr_strerror());
401                 return -1;
402         }
403
404         RIDEBUG("Attributes matching \"%s\"", fmt);
405
406         RINDENT();
407         for (vp = tmpl_cursor_init(NULL, &cursor, request, &vpt);
408              vp;
409              vp = tmpl_cursor_next(&cursor, &vpt)) {
410                 FR_NAME_NUMBER const *type;
411                 char *value;
412
413                 value = vp_aprints_value(vp, vp, '\'');
414                 if (vp->da->flags.has_tag) {
415                         RIDEBUG2("&%s:%s:%i %s %s",
416                                 fr_int2str(pair_lists, vpt.tmpl_list, "<INVALID>"),
417                                 vp->da->name,
418                                 vp->tag,
419                                 fr_int2str(fr_tokens, vp->op, "<INVALID>"),
420                                 value);
421                 } else {
422                         RIDEBUG2("&%s:%s %s %s",
423                                 fr_int2str(pair_lists, vpt.tmpl_list, "<INVALID>"),
424                                 vp->da->name,
425                                 fr_int2str(fr_tokens, vp->op, "<INVALID>"),
426                                 value);
427                 }
428                 talloc_free(value);
429
430                 if (!RDEBUG_ENABLED3) continue;
431
432                 if (vp->da->vendor) {
433                         DICT_VENDOR *dv;
434
435                         dv = dict_vendorbyvalue(vp->da->vendor);
436                         RIDEBUG2("Vendor : %i (%s)", vp->da->vendor, dv ? dv->name : "unknown");
437                 }
438                 RIDEBUG2("Type   : %s", fr_int2str(dict_attr_types, vp->da->type, "<INVALID>"));
439                 RIDEBUG2("Length : %zu", vp->vp_length);
440
441                 if (!RDEBUG_ENABLED4) continue;
442
443                 type = dict_attr_types;
444                 while (type->name) {
445                         int pad;
446
447                         value_data_t *dst = NULL;
448
449                         ssize_t ret;
450
451                         if ((PW_TYPE) type->number == vp->da->type) {
452                                 goto next_type;
453                         }
454
455                         switch (type->number) {
456                         case PW_TYPE_INVALID:           /* Not real type */
457                         case PW_TYPE_MAX:               /* Not real type */
458                         case PW_TYPE_EXTENDED:          /* Not safe/appropriate */
459                         case PW_TYPE_LONG_EXTENDED:     /* Not safe/appropriate */
460                         case PW_TYPE_TLV:               /* Not safe/appropriate */
461                         case PW_TYPE_EVS:               /* Not safe/appropriate */
462                         case PW_TYPE_VSA:               /* @fixme We need special behaviour for these */
463                         case PW_TYPE_COMBO_IP_ADDR:     /* Covered by IPv4 address IPv6 address */
464                         case PW_TYPE_COMBO_IP_PREFIX:   /* Covered by IPv4 address IPv6 address */
465                         case PW_TYPE_TIMEVAL:           /* Not a VALUE_PAIR type */
466                                 goto next_type;
467
468                         default:
469                                 break;
470                         }
471
472                         dst = talloc_zero(vp, value_data_t);
473                         ret = value_data_cast(dst, dst, type->number, NULL, vp->da->type, vp->da,
474                                               &vp->data, vp->vp_length);
475                         if (ret < 0) goto next_type;    /* We expect some to fail */
476
477                         value = value_data_aprints(dst, type->number, NULL, dst, (size_t)ret, '\'');
478                         if (!value) goto next_type;
479
480                         if ((pad = (11 - strlen(type->name))) < 0) {
481                                 pad = 0;
482                         }
483
484                         RINDENT();
485                         RDEBUG2("as %s%*s: %s", type->name, pad, " ", value);
486                         REXDENT();
487
488                 next_type:
489                         talloc_free(dst);
490                         type++;
491                 }
492         }
493
494         *out = '\0';
495         return 0;
496 }
497
498 /** Processes fmt as a map string and applies it to the current request
499  *
500  * e.g. "%{map:&User-Name := 'foo'}"
501  *
502  * Allows sets of modifications to be cached and then applied.
503  * Useful for processing generic attributes from LDAP.
504  */
505 static ssize_t xlat_map(UNUSED void *instance, REQUEST *request,
506                         char const *fmt, char *out, size_t outlen)
507 {
508         vp_map_t *map = NULL;
509         int ret;
510
511         if (map_afrom_attr_str(request, &map, fmt,
512                                REQUEST_CURRENT, PAIR_LIST_REQUEST,
513                                REQUEST_CURRENT, PAIR_LIST_REQUEST) < 0) {
514                 REDEBUG("Failed parsing \"%s\" as map: %s", fmt, fr_strerror());
515                 return -1;
516         }
517
518         RINDENT();
519         ret = map_to_request(request, map, map_to_vp, NULL);
520         REXDENT();
521         talloc_free(map);
522         if (ret < 0) return strlcpy(out, "0", outlen);
523
524         return strlcpy(out, "1", outlen);
525 }
526
527 /** Prints the current module processing the request
528  *
529  */
530 static ssize_t xlat_module(UNUSED void *instance, REQUEST *request,
531                            UNUSED char const *fmt, char *out, size_t outlen)
532 {
533         strlcpy(out, request->module, outlen);
534
535         return strlen(out);
536 }
537
538 #if defined(HAVE_REGEX) && defined(HAVE_PCRE)
539 static ssize_t xlat_regex(UNUSED void *instance, REQUEST *request,
540                           char const *fmt, char *out, size_t outlen)
541 {
542         char *p;
543         size_t len;
544
545         if (regex_request_to_sub_named(request, &p, request, fmt) < 0) {
546                 *out = '\0';
547                 return 0;
548         }
549
550         len = talloc_array_length(p);
551         if (len > outlen) {
552                 RDEBUG("Insufficient buffer space to write subcapture value, needed %zu bytes, have %zu bytes",
553                        len, outlen);
554                 return -1;
555         }
556         strlcpy(out, p, outlen);
557
558         return len - 1; /* - \0 */
559 }
560 #endif
561
562 #ifdef WITH_UNLANG
563 /** Implements the Foreach-Variable-X
564  *
565  * @see modcall()
566  */
567 static ssize_t xlat_foreach(void *instance, REQUEST *request,
568                             UNUSED char const *fmt, char *out, size_t outlen)
569 {
570         VALUE_PAIR      **pvp;
571         size_t          len;
572
573         /*
574          *      See modcall, "FOREACH" for how this works.
575          */
576         pvp = (VALUE_PAIR **) request_data_reference(request, (void *)radius_get_vp, *(int*) instance);
577         if (!pvp || !*pvp) {
578                 *out = '\0';
579                 return 0;
580         }
581
582         len = vp_prints_value(out, outlen, *pvp, 0);
583         if (is_truncated(len, outlen)) {
584                 RDEBUG("Insufficient buffer space to write foreach value");
585                 return -1;
586         }
587
588         return len;
589 }
590 #endif
591
592 /** Print data as string, if possible.
593  *
594  * If attribute "Foo" is defined as "octets" it will normally
595  * be printed as 0x0a0a0a. The xlat "%{string:Foo}" will instead
596  * expand to "\n\n\n"
597  */
598 static ssize_t xlat_string(UNUSED void *instance, REQUEST *request,
599                            char const *fmt, char *out, size_t outlen)
600 {
601         size_t len;
602         ssize_t ret;
603         VALUE_PAIR *vp;
604         uint8_t const *p;
605
606         while (isspace((int) *fmt)) fmt++;
607
608         if (outlen < 3) {
609         nothing:
610                 *out = '\0';
611                 return 0;
612         }
613
614         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) goto nothing;
615
616         ret = rad_vp2data(&p, vp);
617         if (ret < 0) {
618                 return ret;
619         }
620
621         switch (vp->da->type) {
622         case PW_TYPE_OCTETS:
623                 len = fr_prints(out, outlen, (char const *) p, vp->vp_length, '"');
624                 break;
625
626         case PW_TYPE_STRING:
627                 len = strlcpy(out, vp->vp_strvalue, outlen);
628                 break;
629
630         default:
631                 len = fr_prints(out, outlen, (char const *) p, ret, '\0');
632                 break;
633         }
634
635         return len;
636 }
637
638 /** xlat expand string attribute value
639  *
640  */
641 static ssize_t xlat_xlat(UNUSED void *instance, REQUEST *request,
642                         char const *fmt, char *out, size_t outlen)
643 {
644         VALUE_PAIR *vp;
645
646         while (isspace((int) *fmt)) fmt++;
647
648         if (outlen < 3) {
649         nothing:
650                 *out = '\0';
651                 return 0;
652         }
653
654         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) goto nothing;
655
656         return radius_xlat(out, outlen, request, vp->vp_strvalue, NULL, NULL);
657 }
658
659 /** Dynamically change the debugging level for the current request
660  *
661  * Example %{debug:3}
662  */
663 static ssize_t xlat_debug(UNUSED void *instance, REQUEST *request,
664                           char const *fmt, char *out, size_t outlen)
665 {
666         int level = 0;
667
668         /*
669          *  Expand to previous (or current) level
670          */
671         snprintf(out, outlen, "%d", request->log.lvl);
672
673         /*
674          *  Assume we just want to get the current value and NOT set it to 0
675          */
676         if (!*fmt)
677                 goto done;
678
679         level = atoi(fmt);
680         if (level == 0) {
681                 request->log.lvl = RAD_REQUEST_LVL_NONE;
682                 request->log.func = NULL;
683         } else {
684                 if (level > 4) level = 4;
685
686                 request->log.lvl = level;
687                 request->log.func = vradlog_request;
688         }
689
690         done:
691         return strlen(out);
692 }
693
694 /*
695  *      Compare two xlat_t structs, based ONLY on the module name.
696  */
697 static int xlat_cmp(void const *one, void const *two)
698 {
699         xlat_t const *a = one;
700         xlat_t const *b = two;
701
702         if (a->length != b->length) {
703                 return a->length - b->length;
704         }
705
706         return memcmp(a->name, b->name, a->length);
707 }
708
709
710 /*
711  *      find the appropriate registered xlat function.
712  */
713 static xlat_t *xlat_find(char const *name)
714 {
715         xlat_t my_xlat;
716
717         strlcpy(my_xlat.name, name, sizeof(my_xlat.name));
718         my_xlat.length = strlen(my_xlat.name);
719
720         return rbtree_finddata(xlat_root, &my_xlat);
721 }
722
723
724 /** Register an xlat function.
725  *
726  * @param[in] name xlat name.
727  * @param[in] func xlat function to be called.
728  * @param[in] escape function to sanitize any sub expansions passed to the xlat function.
729  * @param[in] instance of module that's registering the xlat function.
730  * @return 0 on success, -1 on failure
731  */
732 int xlat_register(char const *name, xlat_func_t func, xlat_escape_t escape, void *instance)
733 {
734         xlat_t  *c;
735         xlat_t  my_xlat;
736         rbnode_t *node;
737
738         if (!name || !*name) {
739                 DEBUG("xlat_register: Invalid xlat name");
740                 return -1;
741         }
742
743         /*
744          *      First time around, build up the tree...
745          *
746          *      FIXME: This code should be hoisted out of this function,
747          *      and into a global "initialization".  But it isn't critical...
748          */
749         if (!xlat_root) {
750 #ifdef WITH_UNLANG
751                 int i;
752 #endif
753
754                 xlat_root = rbtree_create(NULL, xlat_cmp, NULL, RBTREE_FLAG_REPLACE);
755                 if (!xlat_root) {
756                         DEBUG("xlat_register: Failed to create tree");
757                         return -1;
758                 }
759
760 #ifdef WITH_UNLANG
761                 for (i = 0; xlat_foreach_names[i] != NULL; i++) {
762                         xlat_register(xlat_foreach_names[i],
763                                       xlat_foreach, NULL, &xlat_inst[i]);
764                         c = xlat_find(xlat_foreach_names[i]);
765                         rad_assert(c != NULL);
766                         c->internal = true;
767                 }
768 #endif
769
770 #define XLAT_REGISTER(_x) xlat_register(STRINGIFY(_x), xlat_ ## _x, NULL, NULL); \
771                 c = xlat_find(STRINGIFY(_x)); \
772                 rad_assert(c != NULL); \
773                 c->internal = true
774
775                 XLAT_REGISTER(integer);
776                 XLAT_REGISTER(strlen);
777                 XLAT_REGISTER(length);
778                 XLAT_REGISTER(hex);
779                 XLAT_REGISTER(tag);
780                 XLAT_REGISTER(vendor);
781                 XLAT_REGISTER(vendor_num);
782                 XLAT_REGISTER(attr);
783                 XLAT_REGISTER(attr_num);
784                 XLAT_REGISTER(string);
785                 XLAT_REGISTER(xlat);
786                 XLAT_REGISTER(map);
787                 XLAT_REGISTER(module);
788                 XLAT_REGISTER(debug_attr);
789 #if defined(HAVE_REGEX) && defined(HAVE_PCRE)
790                 XLAT_REGISTER(regex);
791 #endif
792
793                 xlat_register("debug", xlat_debug, NULL, &xlat_inst[0]);
794                 c = xlat_find("debug");
795                 rad_assert(c != NULL);
796                 c->internal = true;
797         }
798
799         /*
800          *      If it already exists, replace the instance.
801          */
802         strlcpy(my_xlat.name, name, sizeof(my_xlat.name));
803         my_xlat.length = strlen(my_xlat.name);
804         c = rbtree_finddata(xlat_root, &my_xlat);
805         if (c) {
806                 if (c->internal) {
807                         DEBUG("xlat_register: Cannot re-define internal xlat");
808                         return -1;
809                 }
810
811                 c->func = func;
812                 c->escape = escape;
813                 c->instance = instance;
814                 return 0;
815         }
816
817         /*
818          *      Doesn't exist.  Create it.
819          */
820         c = talloc_zero(xlat_root, xlat_t);
821
822         c->func = func;
823         c->escape = escape;
824         strlcpy(c->name, name, sizeof(c->name));
825         c->length = strlen(c->name);
826         c->instance = instance;
827
828         node = rbtree_insert_node(xlat_root, c);
829         if (!node) {
830                 talloc_free(c);
831                 return -1;
832         }
833
834         /*
835          *      Ensure that the data is deleted when the node is
836          *      deleted.
837          *
838          *      @todo: Maybe this should be the other way around...
839          *      when a thing IN the tree is deleted, it's automatically
840          *      removed from the tree.  But for now, this works.
841          */
842         (void) talloc_steal(node, c);
843         return 0;
844 }
845
846 /** Unregister an xlat function
847  *
848  * We can only have one function to call per name, so the passing of "func"
849  * here is extraneous.
850  *
851  * @param[in] name xlat to unregister.
852  * @param[in] func unused.
853  * @param[in] instance data.
854  */
855 void xlat_unregister(char const *name, UNUSED xlat_func_t func, void *instance)
856 {
857         xlat_t  *c;
858         xlat_t          my_xlat;
859
860         if (!name || !xlat_root) return;
861
862         strlcpy(my_xlat.name, name, sizeof(my_xlat.name));
863         my_xlat.length = strlen(my_xlat.name);
864
865         c = rbtree_finddata(xlat_root, &my_xlat);
866         if (!c) return;
867
868         if (c->instance != instance) return;
869
870         rbtree_deletebydata(xlat_root, c);
871 }
872
873 static int xlat_unregister_callback(void *instance, void *data)
874 {
875         xlat_t *c = (xlat_t *) data;
876
877         if (c->instance != instance) return 0; /* keep walking */
878
879         return 2;               /* delete it */
880 }
881
882 void xlat_unregister_module(void *instance)
883 {
884         rbtree_walk(xlat_root, RBTREE_DELETE_ORDER, xlat_unregister_callback, instance);
885 }
886
887 /*
888  *      Internal redundant handler for xlats
889  */
890 typedef enum xlat_redundant_type_t {
891         XLAT_INVALID = 0,
892         XLAT_REDUNDANT,
893         XLAT_LOAD_BALANCE,
894         XLAT_REDUNDANT_LOAD_BALANCE,
895 } xlat_redundant_type_t;
896
897 typedef struct xlat_redundant_t {
898         xlat_redundant_type_t type;
899         uint32_t        count;
900         CONF_SECTION *cs;
901 } xlat_redundant_t;
902
903
904 static ssize_t xlat_redundant(void *instance, REQUEST *request,
905                               char const *fmt, char *out, size_t outlen)
906 {
907         xlat_redundant_t *xr = instance;
908         CONF_ITEM *ci;
909         char const *name;
910         xlat_t *xlat;
911
912         rad_assert(xr->type == XLAT_REDUNDANT);
913
914         /*
915          *      Pick the first xlat which succeeds
916          */
917         for (ci = cf_item_find_next(xr->cs, NULL);
918              ci != NULL;
919              ci = cf_item_find_next(xr->cs, ci)) {
920                 ssize_t rcode;
921
922                 if (!cf_item_is_pair(ci)) continue;
923
924                 name = cf_pair_attr(cf_item_to_pair(ci));
925                 rad_assert(name != NULL);
926
927                 xlat = xlat_find(name);
928                 if (!xlat) continue;
929
930                 rcode = xlat->func(xlat->instance, request, fmt, out, outlen);
931                 if (rcode <= 0) continue;
932                 return rcode;
933         }
934
935         /*
936          *      Everything failed.  Oh well.
937          */
938         *out  = 0;
939         return 0;
940 }
941
942
943 static ssize_t xlat_load_balance(void *instance, REQUEST *request,
944                               char const *fmt, char *out, size_t outlen)
945 {
946         uint32_t count = 0;
947         xlat_redundant_t *xr = instance;
948         CONF_ITEM *ci;
949         CONF_ITEM *found = NULL;
950         char const *name;
951         xlat_t *xlat;
952
953         /*
954          *      Choose a child at random.
955          */
956         for (ci = cf_item_find_next(xr->cs, NULL);
957              ci != NULL;
958              ci = cf_item_find_next(xr->cs, ci)) {
959                 if (!cf_item_is_pair(ci)) continue;
960                 count++;
961
962                 /*
963                  *      Replace the previously found one with a random
964                  *      new one.
965                  */
966                 if ((count * (fr_rand() & 0xffff)) < (uint32_t) 0x10000) {
967                         found = ci;
968                 }
969         }
970
971         /*
972          *      Plain load balancing: do one child, and only one child.
973          */
974         if (xr->type == XLAT_LOAD_BALANCE) {
975                 name = cf_pair_attr(cf_item_to_pair(found));
976                 rad_assert(name != NULL);
977
978                 xlat = xlat_find(name);
979                 if (!xlat) return -1;
980
981                 return xlat->func(xlat->instance, request, fmt, out, outlen);
982         }
983
984         rad_assert(xr->type == XLAT_REDUNDANT_LOAD_BALANCE);
985
986         /*
987          *      Try the random one we found.  If it fails, keep going
988          *      through the rest of the children.
989          */
990         ci = found;
991         do {
992                 name = cf_pair_attr(cf_item_to_pair(ci));
993                 rad_assert(name != NULL);
994
995                 xlat = xlat_find(name);
996                 if (xlat) {
997                         ssize_t rcode;
998
999                         rcode = xlat->func(xlat->instance, request, fmt, out, outlen);
1000                         if (rcode > 0) return rcode;
1001                 }
1002
1003                 /*
1004                  *      Go to the next one, wrapping around at the end.
1005                  */
1006                 ci = cf_item_find_next(xr->cs, ci);
1007                 if (!ci) ci = cf_item_find_next(xr->cs, NULL);
1008         } while (ci != found);
1009
1010         return -1;
1011 }
1012
1013
1014 bool xlat_register_redundant(CONF_SECTION *cs)
1015 {
1016         char const *name1, *name2;
1017         xlat_redundant_t *xr;
1018
1019         name1 = cf_section_name1(cs);
1020         name2 = cf_section_name2(cs);
1021
1022         if (!name2) return false;
1023
1024         if (xlat_find(name2)) {
1025                 cf_log_err_cs(cs, "An expansion is already registered for this name");
1026                 return false;
1027         }
1028
1029         xr = talloc_zero(cs, xlat_redundant_t);
1030         if (!xr) return false;
1031
1032         if (strcmp(name1, "redundant") == 0) {
1033                 xr->type = XLAT_REDUNDANT;
1034
1035         } else if (strcmp(name1, "redundant-load-balance") == 0) {
1036                 xr->type = XLAT_REDUNDANT_LOAD_BALANCE;
1037
1038         } else if (strcmp(name1, "load-balance") == 0) {
1039                 xr->type = XLAT_LOAD_BALANCE;
1040
1041         } else {
1042                 return false;
1043         }
1044
1045         xr->cs = cs;
1046
1047         /*
1048          *      Get the number of children for load balancing.
1049          */
1050         if (xr->type == XLAT_REDUNDANT) {
1051                 if (xlat_register(name2, xlat_redundant, NULL, xr) < 0) {
1052                         talloc_free(xr);
1053                         return false;
1054                 }
1055
1056         } else {
1057                 CONF_ITEM *ci;
1058
1059                 for (ci = cf_item_find_next(cs, NULL);
1060                      ci != NULL;
1061                      ci = cf_item_find_next(cs, ci)) {
1062                         if (!cf_item_is_pair(ci)) continue;
1063
1064                         if (!xlat_find(cf_pair_attr(cf_item_to_pair(ci)))) {
1065                                 talloc_free(xr);
1066                                 return false;
1067                         }
1068
1069                         xr->count++;
1070                 }
1071
1072                 if (xlat_register(name2, xlat_load_balance, NULL, xr) < 0) {
1073                         talloc_free(xr);
1074                         return false;
1075                 }
1076         }
1077
1078         return true;
1079 }
1080
1081
1082 /** Crappy temporary function to add attribute ref support to xlats
1083  *
1084  * This needs to die, and hopefully will die, when xlat functions accept
1085  * xlat node structures.
1086  *
1087  * Provides either a pointer to a buffer which contains the value of the reference VALUE_PAIR
1088  * in an architecture independent format. Or a pointer to the start of the fmt string.
1089  *
1090  * The pointer is only guaranteed to be valid between calls to xlat_fmt_to_ref,
1091  * and so long as the source VALUE_PAIR is not freed.
1092  *
1093  * @param out where to write a pointer to the buffer to the data the xlat function needs to work on.
1094  * @param request current request.
1095  * @param fmt string.
1096  * @returns the length of the data or -1 on error.
1097  */
1098 ssize_t xlat_fmt_to_ref(uint8_t const **out, REQUEST *request, char const *fmt)
1099 {
1100         VALUE_PAIR *vp;
1101
1102         while (isspace((int) *fmt)) fmt++;
1103
1104         if (fmt[0] == '&') {
1105                 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
1106                         *out = NULL;
1107                         return -1;
1108                 }
1109
1110                 return rad_vp2data(out, vp);
1111         }
1112
1113         *out = (uint8_t const *)fmt;
1114         return strlen(fmt);
1115 }
1116
1117 /** De-register all xlat functions, used mainly for debugging.
1118  *
1119  */
1120 void xlat_free(void)
1121 {
1122         rbtree_free(xlat_root);
1123 }
1124
1125 #ifdef DEBUG_XLAT
1126 #  define XLAT_DEBUG DEBUG3
1127 #else
1128 #  define XLAT_DEBUG(...)
1129 #endif
1130
1131 static ssize_t xlat_tokenize_expansion(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1132                                        char const **error);
1133 static ssize_t xlat_tokenize_literal(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1134                                      bool brace, char const **error);
1135 static size_t xlat_process(char **out, REQUEST *request, xlat_exp_t const * const head,
1136                            xlat_escape_t escape, void *escape_ctx);
1137
1138 static ssize_t xlat_tokenize_alternation(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1139                                          char const **error)
1140 {
1141         ssize_t slen;
1142         char *p;
1143         xlat_exp_t *node;
1144
1145         rad_assert(fmt[0] == '%');
1146         rad_assert(fmt[1] == '{');
1147         rad_assert(fmt[2] == '%');
1148         rad_assert(fmt[3] == '{');
1149
1150         XLAT_DEBUG("ALTERNATE <-- %s", fmt);
1151
1152         node = talloc_zero(ctx, xlat_exp_t);
1153         node->type = XLAT_ALTERNATE;
1154
1155         p = fmt + 2;
1156         slen = xlat_tokenize_expansion(node, p, &node->child, error);
1157         if (slen <= 0) {
1158                 talloc_free(node);
1159                 return slen - (p - fmt);
1160         }
1161         p += slen;
1162
1163         if (p[0] != ':') {
1164                 talloc_free(node);
1165                 *error = "Expected ':' after first expansion";
1166                 return -(p - fmt);
1167         }
1168         p++;
1169
1170         if (p[0] != '-') {
1171                 talloc_free(node);
1172                 *error = "Expected '-' after ':'";
1173                 return -(p - fmt);
1174         }
1175         p++;
1176
1177         /*
1178          *      Allow the RHS to be empty as a special case.
1179          */
1180         if (*p == '}') {
1181                 /*
1182                  *      Hack up an empty string.
1183                  */
1184                 node->alternate = talloc_zero(node, xlat_exp_t);
1185                 node->alternate->type = XLAT_LITERAL;
1186                 node->alternate->fmt = talloc_typed_strdup(node->alternate, "");
1187                 *(p++) = '\0';
1188
1189         } else {
1190                 slen = xlat_tokenize_literal(node, p,  &node->alternate, true, error);
1191                 if (slen <= 0) {
1192                         talloc_free(node);
1193                         return slen - (p - fmt);
1194                 }
1195
1196                 if (!node->alternate) {
1197                         talloc_free(node);
1198                         *error = "Empty expansion is invalid";
1199                         return -(p - fmt);
1200                 }
1201                 p += slen;
1202         }
1203
1204         *head = node;
1205         return p - fmt;
1206 }
1207
1208 static ssize_t xlat_tokenize_expansion(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1209                                        char const **error)
1210 {
1211         ssize_t slen;
1212         char *p, *q;
1213         xlat_exp_t *node;
1214         long num;
1215
1216         rad_assert(fmt[0] == '%');
1217         rad_assert(fmt[1] == '{');
1218
1219         /*
1220          *      %{%{...}:-bar}
1221          */
1222         if ((fmt[2] == '%') && (fmt[3] == '{')) return xlat_tokenize_alternation(ctx, fmt, head, error);
1223
1224         XLAT_DEBUG("EXPANSION <-- %s", fmt);
1225         node = talloc_zero(ctx, xlat_exp_t);
1226         node->fmt = fmt + 2;
1227         node->len = 0;
1228
1229 #ifdef HAVE_REGEX
1230         /*
1231          *      Handle regex's specially.
1232          */
1233         p = fmt + 2;
1234         num = strtol(p, &q, 10);
1235         if (p != q && (*q == '}')) {
1236                 XLAT_DEBUG("REGEX <-- %s", fmt);
1237                 *q = '\0';
1238
1239                 if ((num > REQUEST_MAX_REGEX) || (num < 0)) {
1240                         talloc_free(node);
1241                         *error = "Invalid regex reference.  Must be in range 0-" STRINGIFY(REQUEST_MAX_REGEX);
1242                         return -2;
1243                 }
1244                 node->attr.tmpl_num = num;
1245
1246                 node->type = XLAT_REGEX;
1247                 *head = node;
1248
1249                 return (q - fmt) + 1;
1250         }
1251 #endif /* HAVE_REGEX */
1252
1253         /*
1254          *      %{Attr-Name}
1255          *      %{Attr-Name[#]}
1256          *      %{Tunnel-Password:1}
1257          *      %{Tunnel-Password:1[#]}
1258          *      %{request:Attr-Name}
1259          *      %{request:Tunnel-Password:1}
1260          *      %{request:Tunnel-Password:1[#]}
1261          *      %{mod:foo}
1262          */
1263
1264         /*
1265          *      This is for efficiency, so we don't search for an xlat,
1266          *      when what's being referenced is obviously an attribute.
1267          */
1268         p = fmt + 2;
1269         for (q = p; *q != '\0'; q++) {
1270                 if (*q == ':') break;
1271
1272                 if (isspace((int) *q)) break;
1273
1274                 if (*q == '[') continue;
1275
1276                 if (*q == '}') break;
1277         }
1278
1279         /*
1280          *      Check for empty expressions %{}
1281          */
1282         if ((*q == '}') && (q == p)) {
1283                 *error = "Empty expression is invalid";
1284                 return -(p - fmt);
1285         }
1286
1287         /*
1288          *      Might be a module name reference.
1289          *
1290          *      If it's not, it's an attribute or parse error.
1291          */
1292         if (*q == ':') {
1293                 *q = '\0';
1294                 node->xlat = xlat_find(node->fmt);
1295                 if (node->xlat) {
1296                         /*
1297                          *      %{mod:foo}
1298                          */
1299                         node->type = XLAT_MODULE;
1300
1301                         p = q + 1;
1302                         XLAT_DEBUG("MOD <-- %s ... %s", node->fmt, p);
1303
1304                         slen = xlat_tokenize_literal(node, p, &node->child, true, error);
1305                         if (slen < 0) {
1306                                 talloc_free(node);
1307                                 return slen - (p - fmt);
1308                         }
1309                         p += slen;
1310
1311                         *head = node;
1312                         rad_assert(node->next == NULL);
1313
1314                         return p - fmt;
1315                 }
1316                 *q = ':';       /* Avoids a strdup */
1317         }
1318
1319         /*
1320          *      The first token ends with:
1321          *      - '[' - Which is an attribute index, so it must be an attribute.
1322          *      - '}' - The end of the expansion, which means it was a bareword.
1323          */
1324         slen = tmpl_from_attr_substr(&node->attr, p, REQUEST_CURRENT, PAIR_LIST_REQUEST, true, true);
1325         if (slen <= 0) {
1326                 /*
1327                  *      If the parse error occurred before the ':'
1328                  *      then the error is changed to 'Unknown module',
1329                  *      as it was more likely to be a bad module name,
1330                  *      than a request qualifier.
1331                  */
1332                 if ((*q == ':') && ((p + (slen * -1)) < q)) {
1333                         *error = "Unknown module";
1334                 } else {
1335                         *error = fr_strerror();
1336                 }
1337
1338                 talloc_free(node);
1339                 return slen - (p - fmt);
1340         }
1341
1342         /*
1343          *      Might be a virtual XLAT attribute
1344          */
1345         if (node->attr.type == TMPL_TYPE_ATTR_UNDEFINED) {
1346                 node->xlat = xlat_find(node->attr.tmpl_unknown_name);
1347                 if (node->xlat) {
1348                         node->type = XLAT_VIRTUAL;
1349                         node->fmt = node->attr.tmpl_unknown_name;
1350
1351                         XLAT_DEBUG("VIRTUAL <-- %s", node->fmt);
1352                         *head = node;
1353                         rad_assert(node->next == NULL);
1354                         q++;
1355                         return q - fmt;
1356                 }
1357
1358                 talloc_free(node);
1359                 *error = "Unknown attribute";
1360                 return -(p - fmt);
1361         }
1362
1363         node->type = XLAT_ATTRIBUTE;
1364         p += slen;
1365
1366         if (*p != '}') {
1367                 talloc_free(node);
1368                 *error = "No matching closing brace";
1369                 return -1;      /* second character of format string */
1370         }
1371         *p++ = '\0';
1372         *head = node;
1373         rad_assert(node->next == NULL);
1374
1375         return p - fmt;
1376 }
1377
1378
1379 static ssize_t xlat_tokenize_literal(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1380                                      bool brace, char const **error)
1381 {
1382         char *p;
1383         xlat_exp_t *node;
1384
1385         if (!*fmt) return 0;
1386
1387         XLAT_DEBUG("LITERAL <-- %s", fmt);
1388
1389         node = talloc_zero(ctx, xlat_exp_t);
1390         node->fmt = fmt;
1391         node->len = 0;
1392         node->type = XLAT_LITERAL;
1393
1394         p = fmt;
1395
1396         while (*p) {
1397                 if (*p == '\\') {
1398                         if (!p[1]) {
1399                                 talloc_free(node);
1400                                 *error = "Invalid escape at end of string";
1401                                 return -(p - fmt);
1402                         }
1403                         p += 2;
1404                         continue;
1405                 }
1406
1407                 /*
1408                  *      Process the expansion.
1409                  */
1410                 if ((p[0] == '%') && (p[1] == '{')) {
1411                         ssize_t slen;
1412
1413                         XLAT_DEBUG("EXPANSION-2 <-- %s", node->fmt);
1414
1415                         slen = xlat_tokenize_expansion(node, p, &node->next, error);
1416                         if (slen <= 0) {
1417                                 talloc_free(node);
1418                                 return slen - (p - fmt);
1419                         }
1420                         *p = '\0'; /* end the literal */
1421                         p += slen;
1422
1423                         rad_assert(node->next != NULL);
1424
1425                         /*
1426                          *      Short-circuit the recursive call.
1427                          *      This saves another function call and
1428                          *      memory allocation.
1429                          */
1430                         if (!*p) break;
1431
1432                         /*
1433                          *      "foo %{User-Name} bar"
1434                          *      LITERAL         "foo "
1435                          *      EXPANSION       User-Name
1436                          *      LITERAL         " bar"
1437                          */
1438                         slen = xlat_tokenize_literal(node->next, p, &(node->next->next), brace, error);
1439                         rad_assert(slen != 0);
1440                         if (slen < 0) {
1441                                 talloc_free(node);
1442                                 return slen - (p - fmt);
1443                         }
1444
1445                         brace = false; /* it was found above, or else the above code errored out */
1446                         p += slen;
1447                         break;  /* stop processing the string */
1448                 }
1449
1450                 /*
1451                  *      Check for valid single-character expansions.
1452                  */
1453                 if (p[0] == '%') {
1454                         ssize_t slen;
1455                         xlat_exp_t *next;
1456
1457                         if (!p[1] || !strchr("%}dlmntDGHISTYv", p[1])) {
1458                                 talloc_free(node);
1459                                 *error = "Invalid variable expansion";
1460                                 p++;
1461                                 return - (p - fmt);
1462                         }
1463
1464                         next = talloc_zero(node, xlat_exp_t);
1465                         next->len = 1;
1466
1467                         switch (p[1]) {
1468                         case '%':
1469                         case '}':
1470                                 next->fmt = talloc_strndup(next, p + 1, 1);
1471
1472                                 XLAT_DEBUG("LITERAL-ESCAPED <-- %s", next->fmt);
1473                                 next->type = XLAT_LITERAL;
1474                                 break;
1475
1476                         default:
1477                                 next->fmt = p + 1;
1478
1479                                 XLAT_DEBUG("PERCENT <-- %c", *next->fmt);
1480                                 next->type = XLAT_PERCENT;
1481                                 break;
1482                         }
1483
1484                         node->next = next;
1485                         *p = '\0';
1486                         p += 2;
1487
1488                         if (!*p) break;
1489
1490                         /*
1491                          *      And recurse.
1492                          */
1493                         slen = xlat_tokenize_literal(node->next, p, &(node->next->next), brace, error);
1494                         rad_assert(slen != 0);
1495                         if (slen < 0) {
1496                                 talloc_free(node);
1497                                 return slen - (p - fmt);
1498                         }
1499
1500                         brace = false; /* it was found above, or else the above code errored out */
1501                         p += slen;
1502                         break;  /* stop processing the string */
1503                 }
1504
1505                 /*
1506                  *      If required, eat the brace.
1507                  */
1508                 if (brace && (*p == '}')) {
1509                         brace = false;
1510                         *p = '\0';
1511                         p++;
1512                         break;
1513                 }
1514
1515                 p++;
1516                 node->len++;
1517         }
1518
1519         /*
1520          *      We were told to look for a brace, but we ran off of
1521          *      the end of the string before we found one.
1522          */
1523         if (brace) {
1524                 *error = "Missing closing brace at end of string";
1525                 return -(p - fmt);
1526         }
1527
1528         /*
1529          *      Squash zero-width literals
1530          */
1531         if (node->len > 0) {
1532                 *head = node;
1533
1534         } else {
1535                 (void) talloc_steal(ctx, node->next);
1536                 *head = node->next;
1537                 talloc_free(node);
1538         }
1539
1540         return p - fmt;
1541 }
1542
1543
1544 static char const xlat_tabs[] = "                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ";
1545
1546 static void xlat_tokenize_debug(xlat_exp_t const *node, int lvl)
1547 {
1548         rad_assert(node != NULL);
1549
1550         if (lvl >= (int) sizeof(xlat_tabs)) lvl = sizeof(xlat_tabs);
1551
1552         while (node) {
1553                 switch (node->type) {
1554                 case XLAT_LITERAL:
1555                         DEBUG("%.*sliteral --> %s", lvl, xlat_tabs, node->fmt);
1556                         break;
1557
1558                 case XLAT_PERCENT:
1559                         DEBUG("%.*spercent --> %c", lvl, xlat_tabs, node->fmt[0]);
1560                         break;
1561
1562                 case XLAT_ATTRIBUTE:
1563                         rad_assert(node->attr.tmpl_da != NULL);
1564                         DEBUG("%.*sattribute --> %s", lvl, xlat_tabs, node->attr.tmpl_da->name);
1565                         rad_assert(node->child == NULL);
1566                         if ((node->attr.tmpl_tag != TAG_ANY) || (node->attr.tmpl_num != NUM_ANY)) {
1567                                 DEBUG("%.*s{", lvl, xlat_tabs);
1568
1569                                 DEBUG("%.*sref  %d", lvl + 1, xlat_tabs, node->attr.tmpl_request);
1570                                 DEBUG("%.*slist %d", lvl + 1, xlat_tabs, node->attr.tmpl_list);
1571
1572                                 if (node->attr.tmpl_tag != TAG_ANY) {
1573                                         DEBUG("%.*stag %d", lvl + 1, xlat_tabs, node->attr.tmpl_tag);
1574                                 }
1575                                 if (node->attr.tmpl_num != NUM_ANY) {
1576                                         if (node->attr.tmpl_num == NUM_COUNT) {
1577                                                 DEBUG("%.*s[#]", lvl + 1, xlat_tabs);
1578                                         } else if (node->attr.tmpl_num == NUM_ALL) {
1579                                                 DEBUG("%.*s[*]", lvl + 1, xlat_tabs);
1580                                         } else {
1581                                                 DEBUG("%.*s[%d]", lvl + 1, xlat_tabs, node->attr.tmpl_num);
1582                                         }
1583                                 }
1584
1585                                 DEBUG("%.*s}", lvl, xlat_tabs);
1586                         }
1587                         break;
1588
1589                 case XLAT_VIRTUAL:
1590                         rad_assert(node->fmt != NULL);
1591                         DEBUG("%.*svirtual --> %s", lvl, xlat_tabs, node->fmt);
1592                         break;
1593
1594                 case XLAT_MODULE:
1595                         rad_assert(node->xlat != NULL);
1596                         DEBUG("%.*sxlat --> %s", lvl, xlat_tabs, node->xlat->name);
1597                         if (node->child) {
1598                                 DEBUG("%.*s{", lvl, xlat_tabs);
1599                                 xlat_tokenize_debug(node->child, lvl + 1);
1600                                 DEBUG("%.*s}", lvl, xlat_tabs);
1601                         }
1602                         break;
1603
1604 #ifdef HAVE_REGEX
1605                 case XLAT_REGEX:
1606                         DEBUG("%.*sregex-var --> %d", lvl, xlat_tabs, node->attr.tmpl_num);
1607                         break;
1608 #endif
1609
1610                 case XLAT_ALTERNATE:
1611                         DEBUG("%.*sif {", lvl, xlat_tabs);
1612                         xlat_tokenize_debug(node->child, lvl + 1);
1613                         DEBUG("%.*s}", lvl, xlat_tabs);
1614                         DEBUG("%.*selse {", lvl, xlat_tabs);
1615                         xlat_tokenize_debug(node->alternate, lvl + 1);
1616                         DEBUG("%.*s}", lvl, xlat_tabs);
1617                         break;
1618                 }
1619                 node = node->next;
1620         }
1621 }
1622
1623 size_t xlat_sprint(char *buffer, size_t bufsize, xlat_exp_t const *node)
1624 {
1625         size_t len;
1626         char *p, *end;
1627
1628         if (!node) {
1629                 *buffer = '\0';
1630                 return 0;
1631         }
1632
1633         p = buffer;
1634         end = buffer + bufsize;
1635
1636         while (node) {
1637                 switch (node->type) {
1638                 case XLAT_LITERAL:
1639                         strlcpy(p, node->fmt, end - p);
1640                         p += strlen(p);
1641                         break;
1642
1643                 case XLAT_PERCENT:
1644                         p[0] = '%';
1645                         p[1] = node->fmt[0];
1646                         p += 2;
1647                         break;
1648
1649                 case XLAT_ATTRIBUTE:
1650                         *(p++) = '%';
1651                         *(p++) = '{';
1652
1653                         if (node->attr.tmpl_request != REQUEST_CURRENT) {
1654                                 strlcpy(p, fr_int2str(request_refs, node->attr.tmpl_request, "??"), end - p);
1655                                 p += strlen(p);
1656                                 *(p++) = '.';
1657                         }
1658
1659                         if ((node->attr.tmpl_request != REQUEST_CURRENT) ||
1660                             (node->attr.tmpl_list != PAIR_LIST_REQUEST)) {
1661                                 strlcpy(p, fr_int2str(pair_lists, node->attr.tmpl_list, "??"), end - p);
1662                                 p += strlen(p);
1663                                 *(p++) = ':';
1664                         }
1665
1666                         strlcpy(p, node->attr.tmpl_da->name, end - p);
1667                         p += strlen(p);
1668
1669                         if (node->attr.tmpl_tag != TAG_ANY) {
1670                                 *(p++) = ':';
1671                                 snprintf(p, end - p, "%u", node->attr.tmpl_tag);
1672                                 p += strlen(p);
1673                         }
1674
1675                         if (node->attr.tmpl_num != NUM_ANY) {
1676                                 *(p++) = '[';
1677                                 switch (node->attr.tmpl_num) {
1678                                 case NUM_COUNT:
1679                                         *(p++) = '#';
1680                                         break;
1681
1682                                 case NUM_ALL:
1683                                         *(p++) = '*';
1684                                         break;
1685
1686                                 default:
1687                                         snprintf(p, end - p, "%i", node->attr.tmpl_num);
1688                                         p += strlen(p);
1689                                 }
1690                                 *(p++) = ']';
1691                         }
1692                         *(p++) = '}';
1693                         break;
1694 #ifdef HAVE_REGEX
1695                 case XLAT_REGEX:
1696                         snprintf(p, end - p, "%%{%i}", node->attr.tmpl_num);
1697                         p += strlen(p);
1698                         break;
1699 #endif
1700                 case XLAT_VIRTUAL:
1701                         *(p++) = '%';
1702                         *(p++) = '{';
1703                         strlcpy(p, node->fmt, end - p);
1704                         p += strlen(p);
1705                         *(p++) = '}';
1706                         break;
1707
1708                 case XLAT_MODULE:
1709                         *(p++) = '%';
1710                         *(p++) = '{';
1711                         strlcpy(p, node->xlat->name, end - p);
1712                         p += strlen(p);
1713                         *(p++) = ':';
1714                         rad_assert(node->child != NULL);
1715                         len = xlat_sprint(p, end - p, node->child);
1716                         p += len;
1717                         *(p++) = '}';
1718                         break;
1719
1720                 case XLAT_ALTERNATE:
1721                         *(p++) = '%';
1722                         *(p++) = '{';
1723
1724                         len = xlat_sprint(p, end - p, node->child);
1725                         p += len;
1726
1727                         *(p++) = ':';
1728                         *(p++) = '-';
1729
1730                         len = xlat_sprint(p, end - p, node->alternate);
1731                         p += len;
1732
1733                         *(p++) = '}';
1734                         break;
1735                 }
1736
1737
1738                 if (p == end) break;
1739
1740                 node = node->next;
1741         }
1742
1743         *p = '\0';
1744
1745         return p - buffer;
1746 }
1747
1748 ssize_t xlat_tokenize(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1749                       char const **error)
1750 {
1751         return xlat_tokenize_literal(ctx, fmt, head, false, error);
1752 }
1753
1754
1755 /** Tokenize an xlat expansion
1756  *
1757  * @param[in] request the input request.  Memory will be attached here.
1758  * @param[in] fmt the format string to expand
1759  * @param[out] head the head of the xlat list / tree structure.
1760  */
1761 static ssize_t xlat_tokenize_request(REQUEST *request, char const *fmt, xlat_exp_t **head)
1762 {
1763         ssize_t slen;
1764         char *tokens;
1765         char const *error = NULL;
1766
1767         *head = NULL;
1768
1769         /*
1770          *      Copy the original format string to a buffer so that
1771          *      the later functions can mangle it in-place, which is
1772          *      much faster.
1773          */
1774         tokens = talloc_typed_strdup(request, fmt);
1775         if (!tokens) return -1;
1776
1777         slen = xlat_tokenize_literal(request, tokens, head, false, &error);
1778
1779         /*
1780          *      Zero length expansion, return a zero length node.
1781          */
1782         if (slen == 0) {
1783                 *head = talloc_zero(request, xlat_exp_t);
1784         }
1785
1786         /*
1787          *      Output something like:
1788          *
1789          *      "format string"
1790          *      "       ^ error was here"
1791          */
1792         if (slen < 0) {
1793                 talloc_free(tokens);
1794                 rad_assert(error != NULL);
1795
1796                 REMARKER(fmt, -slen, error);
1797                 return slen;
1798         }
1799
1800         if (*head && (rad_debug_lvl > 2)) {
1801                 DEBUG("%s", fmt);
1802                 DEBUG("Parsed xlat tree:");
1803                 xlat_tokenize_debug(*head, 0);
1804         }
1805
1806         /*
1807          *      All of the nodes point to offsets in the "tokens"
1808          *      string.  Let's ensure that free'ing head will free
1809          *      "tokens", too.
1810          */
1811         (void) talloc_steal(*head, tokens);
1812
1813         return slen;
1814 }
1815
1816
1817 static char *xlat_getvp(TALLOC_CTX *ctx, REQUEST *request, vp_tmpl_t const *vpt,
1818                         bool escape, bool return_null)
1819 {
1820         VALUE_PAIR *vp = NULL, *virtual = NULL;
1821         RADIUS_PACKET *packet = NULL;
1822         DICT_VALUE *dv;
1823         char *ret = NULL;
1824
1825         vp_cursor_t cursor;
1826         char quote = escape ? '"' : '\0';
1827
1828         rad_assert((vpt->type == TMPL_TYPE_ATTR) || (vpt->type == TMPL_TYPE_LIST));
1829
1830         /*
1831          *      We only support count and concatenate operations on lists.
1832          */
1833         if (vpt->type == TMPL_TYPE_LIST) {
1834                 vp = tmpl_cursor_init(NULL, &cursor, request, vpt);
1835                 goto do_print;
1836         }
1837
1838         /*
1839          *      See if we're dealing with an attribute in the request
1840          *
1841          *      This allows users to manipulate virtual attributes as if
1842          *      they were real ones.
1843          */
1844         vp = tmpl_cursor_init(NULL, &cursor, request, vpt);
1845         if (vp) goto do_print;
1846
1847         /*
1848          *      We didn't find the VP in a list.
1849          *      If it's not a virtual one, and we're not meant to
1850          *      be counting it, return.
1851          */
1852         if (!vpt->tmpl_da->flags.virtual) {
1853                 if (vpt->tmpl_num == NUM_COUNT) goto do_print;
1854                 return NULL;
1855         }
1856
1857         /*
1858          *      Switch out the request to the one specified by the template
1859          */
1860         if (radius_request(&request, vpt->tmpl_request) < 0) return NULL;
1861
1862         /*
1863          *      Some non-packet expansions
1864          */
1865         switch (vpt->tmpl_da->attr) {
1866         default:
1867                 break;          /* ignore them */
1868
1869         case PW_CLIENT_SHORTNAME:
1870                 if (vpt->tmpl_num == NUM_COUNT) goto count_virtual;
1871                 if (request->client && request->client->shortname) {
1872                         return talloc_typed_strdup(ctx, request->client->shortname);
1873                 }
1874                 return talloc_typed_strdup(ctx, "<UNKNOWN-CLIENT>");
1875
1876         case PW_REQUEST_PROCESSING_STAGE:
1877                 if (vpt->tmpl_num == NUM_COUNT) goto count_virtual;
1878                 if (request->component) {
1879                         return talloc_typed_strdup(ctx, request->component);
1880                 }
1881                 return talloc_typed_strdup(ctx, "server_core");
1882
1883         case PW_VIRTUAL_SERVER:
1884                 if (vpt->tmpl_num == NUM_COUNT) goto count_virtual;
1885                 if (!request->server) return NULL;
1886                 return talloc_typed_strdup(ctx, request->server);
1887
1888         case PW_MODULE_RETURN_CODE:
1889                 if (vpt->tmpl_num == NUM_COUNT) goto count_virtual;
1890                 if (!request->rcode) return NULL;
1891                 return talloc_typed_strdup(ctx, fr_int2str(modreturn_table, request->rcode, ""));
1892         }
1893
1894         /*
1895          *      All of the attributes must now refer to a packet.
1896          *      If there's no packet, we can't print any attribute
1897          *      referencing it.
1898          */
1899         packet = radius_packet(request, vpt->tmpl_list);
1900         if (!packet) {
1901                 if (return_null) return NULL;
1902                 return vp_aprints_type(ctx, vpt->tmpl_da->type);
1903         }
1904
1905         vp = NULL;
1906         switch (vpt->tmpl_da->attr) {
1907         default:
1908                 break;
1909
1910         case PW_PACKET_TYPE:
1911                 dv = dict_valbyattr(PW_PACKET_TYPE, 0, packet->code);
1912                 if (dv) return talloc_typed_strdup(ctx, dv->name);
1913                 return talloc_typed_asprintf(ctx, "%d", packet->code);
1914
1915         case PW_RESPONSE_PACKET_TYPE:
1916         {
1917                 int code = 0;
1918
1919 #ifdef WITH_PROXY
1920                 if (request->proxy_reply && (!request->reply || !request->reply->code)) {
1921                         code = request->proxy_reply->code;
1922                 } else
1923 #endif
1924                         if (request->reply) {
1925                                 code = request->reply->code;
1926                         }
1927
1928                 return talloc_typed_strdup(ctx, fr_packet_codes[code]);
1929         }
1930
1931         /*
1932          *      Virtual attributes which require a temporary VALUE_PAIR
1933          *      to be allocated. We can't use stack allocated memory
1934          *      because of the talloc checks sprinkled throughout the
1935          *      various VP functions.
1936          */
1937         case PW_PACKET_AUTHENTICATION_VECTOR:
1938                 virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1939                 fr_pair_value_memcpy(virtual, packet->vector, sizeof(packet->vector));
1940                 vp = virtual;
1941                 break;
1942
1943         case PW_CLIENT_IP_ADDRESS:
1944         case PW_PACKET_SRC_IP_ADDRESS:
1945                 if (packet->src_ipaddr.af == AF_INET) {
1946                         virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1947                         virtual->vp_ipaddr = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
1948                         vp = virtual;
1949                 }
1950                 break;
1951
1952         case PW_PACKET_DST_IP_ADDRESS:
1953                 if (packet->dst_ipaddr.af == AF_INET) {
1954                         virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1955                         virtual->vp_ipaddr = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
1956                         vp = virtual;
1957                 }
1958                 break;
1959
1960         case PW_PACKET_SRC_IPV6_ADDRESS:
1961                 if (packet->src_ipaddr.af == AF_INET6) {
1962                         virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1963                         memcpy(&virtual->vp_ipv6addr,
1964                                &packet->src_ipaddr.ipaddr.ip6addr,
1965                                sizeof(packet->src_ipaddr.ipaddr.ip6addr));
1966                         vp = virtual;
1967                 }
1968                 break;
1969
1970         case PW_PACKET_DST_IPV6_ADDRESS:
1971                 if (packet->dst_ipaddr.af == AF_INET6) {
1972                         virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1973                         memcpy(&virtual->vp_ipv6addr,
1974                                &packet->dst_ipaddr.ipaddr.ip6addr,
1975                                sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
1976                         vp = virtual;
1977                 }
1978                 break;
1979
1980         case PW_PACKET_SRC_PORT:
1981                 virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1982                 virtual->vp_integer = packet->src_port;
1983                 vp = virtual;
1984                 break;
1985
1986         case PW_PACKET_DST_PORT:
1987                 virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1988                 virtual->vp_integer = packet->dst_port;
1989                 vp = virtual;
1990                 break;
1991         }
1992
1993         /*
1994          *      Fake various operations for virtual attributes.
1995          */
1996         if (virtual) {
1997                 if (vpt->tmpl_num != NUM_ANY) switch (vpt->tmpl_num) {
1998                 /*
1999                  *      [n] is NULL (we only have [0])
2000                  */
2001                 default:
2002                         goto finish;
2003                 /*
2004                  *      [*] means only one.
2005                  */
2006                 case NUM_ALL:
2007                         break;
2008
2009                 /*
2010                  *      [#] means 1 (as there's only one)
2011                  */
2012                 case NUM_COUNT:
2013                 count_virtual:
2014                         ret = talloc_strdup(ctx, "1");
2015                         goto finish;
2016
2017                 /*
2018                  *      [0] is fine (get the first instance)
2019                  */
2020                 case 0:
2021                         break;
2022                 }
2023                 goto print;
2024         }
2025
2026 do_print:
2027         switch (vpt->tmpl_num) {
2028         /*
2029          *      Return a count of the VPs.
2030          */
2031         case NUM_COUNT:
2032         {
2033                 int count = 0;
2034
2035                 for (vp = tmpl_cursor_init(NULL, &cursor, request, vpt);
2036                      vp;
2037                      vp = tmpl_cursor_next(&cursor, vpt)) count++;
2038
2039                 return talloc_typed_asprintf(ctx, "%d", count);
2040         }
2041
2042
2043         /*
2044          *      Concatenate all values together,
2045          *      separated by commas.
2046          */
2047         case NUM_ALL:
2048         {
2049                 char *p, *q;
2050
2051                 if (!fr_cursor_current(&cursor)) return NULL;
2052                 p = vp_aprints_value(ctx, vp, quote);
2053                 if (!p) return NULL;
2054
2055                 while ((vp = tmpl_cursor_next(&cursor, vpt)) != NULL) {
2056                         q = vp_aprints_value(ctx, vp, quote);
2057                         if (!q) return NULL;
2058                         p = talloc_strdup_append(p, ",");
2059                         p = talloc_strdup_append(p, q);
2060                 }
2061
2062                 return p;
2063         }
2064
2065         default:
2066                 /*
2067                  *      The cursor was set to the correct
2068                  *      position above by tmpl_cursor_init.
2069                  */
2070                 vp = fr_cursor_current(&cursor);
2071                 break;
2072         }
2073
2074         if (!vp) {
2075                 if (return_null) return NULL;
2076                 return vp_aprints_type(ctx, vpt->tmpl_da->type);
2077         }
2078
2079 print:
2080         ret = vp_aprints_value(ctx, vp, quote);
2081
2082 finish:
2083         talloc_free(virtual);
2084         return ret;
2085 }
2086
2087 #ifdef DEBUG_XLAT
2088 static const char xlat_spaces[] = "                                                                                                                                                                                                                                                                ";
2089 #endif
2090
2091 static char *xlat_aprint(TALLOC_CTX *ctx, REQUEST *request, xlat_exp_t const * const node,
2092                          xlat_escape_t escape, void *escape_ctx, int lvl)
2093 {
2094         ssize_t rcode;
2095         char *str = NULL, *child;
2096         char const *p;
2097
2098         XLAT_DEBUG("%.*sxlat aprint %d %s", lvl, xlat_spaces, node->type, node->fmt);
2099
2100         switch (node->type) {
2101                 /*
2102                  *      Don't escape this.
2103                  */
2104         case XLAT_LITERAL:
2105                 XLAT_DEBUG("xlat_aprint LITERAL");
2106                 return talloc_typed_strdup(ctx, node->fmt);
2107
2108                 /*
2109                  *      Do a one-character expansion.
2110                  */
2111         case XLAT_PERCENT:
2112         {
2113                 char *nl;
2114                 size_t freespace = 256;
2115                 struct tm ts;
2116                 time_t when;
2117
2118                 XLAT_DEBUG("xlat_aprint PERCENT");
2119
2120                 str = talloc_array(ctx, char, freespace); /* @todo do better allocation */
2121                 p = node->fmt;
2122
2123                 when = request->timestamp;
2124                 if (request->packet) {
2125                         when = request->packet->timestamp.tv_sec;
2126                 }
2127
2128                 switch (*p) {
2129                 case '%':
2130                         str[0] = '%';
2131                         str[1] = '\0';
2132                         break;
2133
2134                 case 'd': /* request day */
2135                         if (!localtime_r(&when, &ts)) goto error;
2136                         strftime(str, freespace, "%d", &ts);
2137                         break;
2138
2139                 case 'l': /* request timestamp */
2140                         snprintf(str, freespace, "%lu",
2141                                  (unsigned long) when);
2142                         break;
2143
2144                 case 'm': /* request month */
2145                         if (!localtime_r(&when, &ts)) goto error;
2146                         strftime(str, freespace, "%m", &ts);
2147                         break;
2148
2149                 case 'n': /* Request Number*/
2150                         snprintf(str, freespace, "%u", request->number);
2151                         break;
2152
2153                 case 't': /* request timestamp */
2154                         CTIME_R(&when, str, freespace);
2155                         nl = strchr(str, '\n');
2156                         if (nl) *nl = '\0';
2157                         break;
2158
2159                 case 'D': /* request date */
2160                         if (!localtime_r(&when, &ts)) goto error;
2161                         strftime(str, freespace, "%Y%m%d", &ts);
2162                         break;
2163
2164                 case 'G': /* request minute */
2165                         if (!localtime_r(&when, &ts)) goto error;
2166                         strftime(str, freespace, "%M", &ts);
2167                         break;
2168
2169                 case 'H': /* request hour */
2170                         if (!localtime_r(&when, &ts)) goto error;
2171                         strftime(str, freespace, "%H", &ts);
2172                         break;
2173
2174                 case 'I': /* Request ID */
2175                         if (request->packet) {
2176                                 snprintf(str, freespace, "%i", request->packet->id);
2177                         }
2178                         break;
2179
2180                 case 'S': /* request timestamp in SQL format*/
2181                         if (!localtime_r(&when, &ts)) goto error;
2182                         strftime(str, freespace, "%Y-%m-%d %H:%M:%S", &ts);
2183                         break;
2184
2185                 case 'T': /* request timestamp */
2186                         if (!localtime_r(&when, &ts)) goto error;
2187                         strftime(str, freespace, "%Y-%m-%d-%H.%M.%S.000000", &ts);
2188                         break;
2189
2190                 case 'Y': /* request year */
2191                         if (!localtime_r(&when, &ts)) {
2192                                 error:
2193                                 REDEBUG("Failed converting packet timestamp to localtime: %s", fr_syserror(errno));
2194                                 talloc_free(str);
2195                                 return NULL;
2196                         }
2197                         strftime(str, freespace, "%Y", &ts);
2198                         break;
2199
2200                 case 'v': /* Version of code */
2201                         RWDEBUG("%%v is deprecated and will be removed.  Use ${version.freeradius-server}");
2202                         snprintf(str, freespace, "%s", radiusd_version_short);
2203                         break;
2204
2205                 default:
2206                         rad_assert(0 == 1);
2207                         break;
2208                 }
2209         }
2210                 break;
2211
2212         case XLAT_ATTRIBUTE:
2213                 XLAT_DEBUG("xlat_aprint ATTRIBUTE");
2214
2215                 /*
2216                  *      Some attributes are virtual <sigh>
2217                  */
2218                 str = xlat_getvp(ctx, request, &node->attr, escape ? false : true, true);
2219                 if (str) {
2220                         XLAT_DEBUG("EXPAND attr %s", node->attr.tmpl_da->name);
2221                         XLAT_DEBUG("       ---> %s", str);
2222                 }
2223                 break;
2224
2225         case XLAT_VIRTUAL:
2226                 XLAT_DEBUG("xlat_aprint VIRTUAL");
2227                 str = talloc_array(ctx, char, 2048); /* FIXME: have the module call talloc_typed_asprintf */
2228                 rcode = node->xlat->func(node->xlat->instance, request, NULL, str, 2048);
2229                 if (rcode < 0) {
2230                         talloc_free(str);
2231                         return NULL;
2232                 }
2233                 RDEBUG2("EXPAND %s", node->xlat->name);
2234                 RDEBUG2("   --> %s", str);
2235                 break;
2236
2237         case XLAT_MODULE:
2238                 XLAT_DEBUG("xlat_aprint MODULE");
2239
2240                 if (node->child) {
2241                         if (xlat_process(&child, request, node->child, node->xlat->escape, node->xlat->instance) == 0) {
2242                                 return NULL;
2243                         }
2244
2245                         XLAT_DEBUG("%.*sEXPAND mod %s %s", lvl, xlat_spaces, node->fmt, node->child->fmt);
2246                 } else {
2247                         XLAT_DEBUG("%.*sEXPAND mod %s", lvl, xlat_spaces, node->fmt);
2248                         child = talloc_typed_strdup(ctx, "");
2249                 }
2250
2251                 XLAT_DEBUG("%.*s      ---> %s", lvl, xlat_spaces, child);
2252
2253                 /*
2254                  *      Smash \n --> CR.
2255                  *
2256                  *      The OUTPUT of xlat is a printable string.  The INPUT might not be...
2257                  *
2258                  *      This is really the reverse of fr_prints().
2259                  */
2260                 if (cf_new_escape && *child) {
2261                         ssize_t slen;
2262                         PW_TYPE type;
2263                         value_data_t data;
2264
2265                         type = PW_TYPE_STRING;
2266                         slen = value_data_from_str(request, &data, &type, NULL, child, talloc_array_length(child) - 1, '"');
2267                         if (slen <= 0) {
2268                                 talloc_free(child);
2269                                 return NULL;
2270                         }
2271
2272                         talloc_free(child);
2273                         child = data.ptr;
2274
2275                 } else {
2276                         char *q;
2277
2278                         p = q = child;
2279                         while (*p) {
2280                                 if (*p == '\\') switch (p[1]) {
2281                                         default:
2282                                                 *(q++) = p[1];
2283                                                 p += 2;
2284                                                 continue;
2285
2286                                         case 'n':
2287                                                 *(q++) = '\n';
2288                                                 p += 2;
2289                                                 continue;
2290
2291                                         case 't':
2292                                                 *(q++) = '\t';
2293                                                 p += 2;
2294                                                 continue;
2295                                         }
2296
2297                                 *(q++) = *(p++);
2298                         }
2299                         *q = '\0';
2300                 }
2301
2302                 str = talloc_array(ctx, char, 2048); /* FIXME: have the module call talloc_typed_asprintf */
2303                 *str = '\0';    /* Be sure the string is NULL terminated, we now only free on error */
2304
2305                 rcode = node->xlat->func(node->xlat->instance, request, child, str, 2048);
2306                 talloc_free(child);
2307                 if (rcode < 0) {
2308                         talloc_free(str);
2309                         return NULL;
2310                 }
2311                 break;
2312
2313 #ifdef HAVE_REGEX
2314         case XLAT_REGEX:
2315                 XLAT_DEBUG("xlat_aprint REGEX");
2316                 if (regex_request_to_sub(ctx, &str, request, node->attr.tmpl_num) < 0) return NULL;
2317
2318                 break;
2319 #endif
2320
2321         case XLAT_ALTERNATE:
2322                 XLAT_DEBUG("xlat_aprint ALTERNATE");
2323                 rad_assert(node->child != NULL);
2324                 rad_assert(node->alternate != NULL);
2325
2326                 str = xlat_aprint(ctx, request, node->child, escape, escape_ctx, lvl);
2327                 if (str) {
2328                         XLAT_DEBUG("ALTERNATE got string: %s", str);
2329                         break;
2330                 }
2331
2332                 XLAT_DEBUG("ALTERNATE going to alternate");
2333                 str = xlat_aprint(ctx, request, node->alternate, escape, escape_ctx, lvl);
2334                 break;
2335
2336         }
2337
2338         /*
2339          *      If there's no data, return that, instead of an empty string.
2340          */
2341         if (str && !str[0]) {
2342                 talloc_free(str);
2343                 return NULL;
2344         }
2345
2346         /*
2347          *      Escape the non-literals we found above.
2348          */
2349         if (str && escape) {
2350                 char *escaped;
2351
2352                 escaped = talloc_array(ctx, char, 2048); /* FIXME: do something intelligent */
2353                 escape(request, escaped, 2038, str, escape_ctx);
2354                 talloc_free(str);
2355                 str = escaped;
2356         }
2357
2358         return str;
2359 }
2360
2361
2362 static size_t xlat_process(char **out, REQUEST *request, xlat_exp_t const * const head,
2363                            xlat_escape_t escape, void *escape_ctx)
2364 {
2365         int i, list;
2366         size_t total;
2367         char **array, *answer;
2368         xlat_exp_t const *node;
2369
2370         *out = NULL;
2371
2372         /*
2373          *      There are no nodes to process, so the result is a zero
2374          *      length string.
2375          */
2376         if (!head) {
2377                 *out = talloc_zero_array(request, char, 1);
2378                 return 0;
2379         }
2380
2381         /*
2382          *      Hack for speed.  If it's one expansion, just allocate
2383          *      that and return, instead of allocating an intermediary
2384          *      array.
2385          */
2386         if (!head->next) {
2387                 /*
2388                  *      Pass the MAIN escape function.  Recursive
2389                  *      calls will call node-specific escape
2390                  *      functions.
2391                  */
2392                 answer = xlat_aprint(request, request, head, escape, escape_ctx, 0);
2393                 if (!answer) {
2394                         *out = talloc_zero_array(request, char, 1);
2395                         return 0;
2396                 }
2397                 *out = answer;
2398                 return strlen(answer);
2399         }
2400
2401         list = 0;               /* FIXME: calculate this once */
2402         for (node = head; node != NULL; node = node->next) {
2403                 list++;
2404         }
2405
2406         array = talloc_array(request, char *, list);
2407         if (!array) return -1;
2408
2409         for (node = head, i = 0; node != NULL; node = node->next, i++) {
2410                 array[i] = xlat_aprint(array, request, node, escape, escape_ctx, 0); /* may be NULL */
2411         }
2412
2413         total = 0;
2414         for (i = 0; i < list; i++) {
2415                 if (array[i]) total += strlen(array[i]); /* FIXME: calculate strlen once */
2416         }
2417
2418         if (!total) {
2419                 talloc_free(array);
2420                 *out = talloc_zero_array(request, char, 1);
2421                 return 0;
2422         }
2423
2424         answer = talloc_array(request, char, total + 1);
2425
2426         total = 0;
2427         for (i = 0; i < list; i++) {
2428                 size_t len;
2429
2430                 if (array[i]) {
2431                         len = strlen(array[i]);
2432                         memcpy(answer + total, array[i], len);
2433                         total += len;
2434                 }
2435         }
2436         answer[total] = '\0';
2437         talloc_free(array);     /* and child entries */
2438
2439         *out = answer;
2440         return total;
2441 }
2442
2443
2444 /** Replace %whatever in a string.
2445  *
2446  * See 'doc/variables.txt' for more information.
2447  *
2448  * @param[out] out Where to write pointer to output buffer.
2449  * @param[in] outlen Size of out.
2450  * @param[in] request current request.
2451  * @param[in] node the xlat structure to expand
2452  * @param[in] escape function to escape final value e.g. SQL quoting.
2453  * @param[in] escape_ctx pointer to pass to escape function.
2454  * @return length of string written @bug should really have -1 for failure
2455  */
2456 static ssize_t xlat_expand_struct(char **out, size_t outlen, REQUEST *request, xlat_exp_t const *node,
2457                                   xlat_escape_t escape, void *escape_ctx)
2458 {
2459         char *buff;
2460         ssize_t len;
2461
2462         rad_assert(node != NULL);
2463
2464         len = xlat_process(&buff, request, node, escape, escape_ctx);
2465         if ((len < 0) || !buff) {
2466                 rad_assert(buff == NULL);
2467                 if (*out) *out[0] = '\0';
2468                 return len;
2469         }
2470
2471         len = strlen(buff);
2472         /*
2473          *      If out doesn't point to an existing buffer
2474          *      copy the pointer to our buffer over.
2475          */
2476         if (!*out) {
2477                 *out = buff;
2478                 return len;
2479         }
2480
2481         /*
2482          *      Otherwise copy the malloced buffer to the fixed one.
2483          */
2484         strlcpy(*out, buff, outlen);
2485         talloc_free(buff);
2486         return len;
2487 }
2488
2489 static ssize_t xlat_expand(char **out, size_t outlen, REQUEST *request, char const *fmt,
2490                            xlat_escape_t escape, void *escape_ctx) CC_HINT(nonnull (1, 3, 4));
2491
2492 /** Replace %whatever in a string.
2493  *
2494  * See 'doc/variables.txt' for more information.
2495  *
2496  * @param[out] out Where to write pointer to output buffer.
2497  * @param[in] outlen Size of out.
2498  * @param[in] request current request.
2499  * @param[in] fmt string to expand.
2500  * @param[in] escape function to escape final value e.g. SQL quoting.
2501  * @param[in] escape_ctx pointer to pass to escape function.
2502  * @return length of string written @bug should really have -1 for failure
2503  */
2504 static ssize_t xlat_expand(char **out, size_t outlen, REQUEST *request, char const *fmt,
2505                            xlat_escape_t escape, void *escape_ctx)
2506 {
2507         ssize_t len;
2508         xlat_exp_t *node;
2509
2510         /*
2511          *      Give better errors than the old code.
2512          */
2513         len = xlat_tokenize_request(request, fmt, &node);
2514         if (len == 0) {
2515                 if (*out) {
2516                         *out[0] = '\0';
2517                 } else {
2518                         *out = talloc_zero_array(request, char, 1);
2519                 }
2520                 return 0;
2521         }
2522
2523         if (len < 0) {
2524                 if (*out) *out[0] = '\0';
2525                 return -1;
2526         }
2527
2528         len = xlat_expand_struct(out, outlen, request, node, escape, escape_ctx);
2529         talloc_free(node);
2530
2531         RDEBUG2("EXPAND %s", fmt);
2532         RDEBUG2("   --> %s", *out);
2533
2534         return len;
2535 }
2536
2537 /** Try to convert an xlat to a tmpl for efficiency
2538  *
2539  * @param ctx to allocate new vp_tmpl_t in.
2540  * @param node to convert.
2541  * @return NULL if unable to convert (not necessarily error), or a new vp_tmpl_t.
2542  */
2543 vp_tmpl_t *xlat_to_tmpl_attr(TALLOC_CTX *ctx, xlat_exp_t *node)
2544 {
2545         vp_tmpl_t *vpt;
2546
2547         if (node->next || (node->type != XLAT_ATTRIBUTE) || (node->attr.type != TMPL_TYPE_ATTR)) return NULL;
2548
2549         /*
2550          *   Concat means something completely different as an attribute reference
2551          *   Count isn't implemented.
2552          */
2553         if ((node->attr.tmpl_num == NUM_COUNT) || (node->attr.tmpl_num == NUM_ALL)) return NULL;
2554
2555         vpt = tmpl_alloc(ctx, TMPL_TYPE_ATTR, node->fmt, -1);
2556         if (!vpt) return NULL;
2557         memcpy(&vpt->data, &node->attr.data, sizeof(vpt->data));
2558
2559         VERIFY_TMPL(vpt);
2560
2561         return vpt;
2562 }
2563
2564 /** Try to convert attr tmpl to an xlat for &attr[*] and artificially constructing expansions
2565  *
2566  * @param ctx to allocate new xlat_expt_t in.
2567  * @param vpt to convert.
2568  * @return NULL if unable to convert (not necessarily error), or a new vp_tmpl_t.
2569  */
2570 xlat_exp_t *xlat_from_tmpl_attr(TALLOC_CTX *ctx, vp_tmpl_t *vpt)
2571 {
2572         xlat_exp_t *node;
2573
2574         if (vpt->type != TMPL_TYPE_ATTR) return NULL;
2575
2576         node = talloc_zero(ctx, xlat_exp_t);
2577         node->type = XLAT_ATTRIBUTE;
2578         node->fmt = talloc_bstrndup(node, vpt->name, vpt->len);
2579         tmpl_init(&node->attr, TMPL_TYPE_ATTR, node->fmt, talloc_array_length(node->fmt) - 1);
2580         memcpy(&node->attr.data, &vpt->data, sizeof(vpt->data));
2581
2582         return node;
2583 }
2584
2585 ssize_t radius_xlat(char *out, size_t outlen, REQUEST *request, char const *fmt, xlat_escape_t escape, void *ctx)
2586 {
2587         return xlat_expand(&out, outlen, request, fmt, escape, ctx);
2588 }
2589
2590 ssize_t radius_xlat_struct(char *out, size_t outlen, REQUEST *request, xlat_exp_t const *xlat, xlat_escape_t escape, void *ctx)
2591 {
2592         return xlat_expand_struct(&out, outlen, request, xlat, escape, ctx);
2593 }
2594
2595 ssize_t radius_axlat(char **out, REQUEST *request, char const *fmt, xlat_escape_t escape, void *ctx)
2596 {
2597         return xlat_expand(out, 0, request, fmt, escape, ctx);
2598 }
2599
2600 ssize_t radius_axlat_struct(char **out, REQUEST *request, xlat_exp_t const *xlat, xlat_escape_t escape, void *ctx)
2601 {
2602         return xlat_expand_struct(out, 0, request, xlat, escape, ctx);
2603 }