More minor doxygen fixes
[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 typedef struct xlat_t {
36         char                    name[MAX_STRING_LEN];   //!< Name of the xlat expansion.
37         int                     length;                 //!< Length of name.
38         void                    *instance;              //!< Module instance passed to xlat and escape functions.
39         RAD_XLAT_FUNC           func;                   //!< xlat function.
40         RADIUS_ESCAPE_STRING    escape;                 //!< Escape function to apply to dynamic input to func.
41         bool                    internal;               //!< If true, cannot be redefined.
42 } xlat_t;
43
44 typedef enum {
45         XLAT_LITERAL,           //!< Literal string
46         XLAT_PERCENT,           //!< Literal string with %v
47         XLAT_MODULE,            //!< xlat module
48         XLAT_VIRTUAL,           //!< virtual attribute
49         XLAT_ATTRIBUTE,         //!< xlat attribute
50 #ifdef HAVE_REGEX
51         XLAT_REGEX,             //!< regex reference
52 #endif
53         XLAT_ALTERNATE          //!< xlat conditional syntax :-
54 } xlat_state_t;
55
56 struct xlat_exp {
57         char const *fmt;        //!< The format string.
58         size_t len;             //!< Length of the format string.
59
60         xlat_state_t type;      //!< type of this expansion.
61         xlat_exp_t *next;       //!< Next in the list.
62
63         xlat_exp_t *child;      //!< Nested expansion.
64         xlat_exp_t *alternate;  //!< Alternative expansion if this one expanded to a zero length string.
65
66         value_pair_tmpl_t attr; //!< An attribute template.
67         xlat_t const *xlat;     //!< The xlat expansion to expand format with.
68 };
69
70 typedef struct xlat_out {
71         char const *out;        //!< Output data.
72         size_t len;             //!< Length of the output string.
73 } xlat_out_t;
74
75 static rbtree_t *xlat_root = NULL;
76
77 #ifdef WITH_UNLANG
78 static char const * const xlat_foreach_names[] = {"Foreach-Variable-0",
79                                                   "Foreach-Variable-1",
80                                                   "Foreach-Variable-2",
81                                                   "Foreach-Variable-3",
82                                                   "Foreach-Variable-4",
83                                                   "Foreach-Variable-5",
84                                                   "Foreach-Variable-6",
85                                                   "Foreach-Variable-7",
86                                                   "Foreach-Variable-8",
87                                                   "Foreach-Variable-9",
88                                                   NULL};
89 #endif
90
91 #if REQUEST_MAX_REGEX > 8
92 #error Please fix the following line
93 #endif
94 static int xlat_inst[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; /* up to 8 for regex */
95
96 char const *radiusd_short_version = RADIUSD_VERSION_STRING;
97
98 /** Print length of its RHS.
99  *
100  */
101 static ssize_t xlat_strlen(UNUSED void *instance, UNUSED REQUEST *request,
102                            char const *fmt, char *out, size_t outlen)
103 {
104         snprintf(out, outlen, "%u", (unsigned int) strlen(fmt));
105         return strlen(out);
106 }
107
108 /** Print the size of the attribute in bytes.
109  *
110  */
111 static ssize_t xlat_length(UNUSED void *instance, UNUSED REQUEST *request,
112                            char const *fmt, char *out, size_t outlen)
113 {
114         VALUE_PAIR *vp;
115         while (isspace((int) *fmt)) fmt++;
116
117         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
118                 *out = '\0';
119                 return 0;
120         }
121
122         snprintf(out, outlen, "%zu", vp->length);
123         return strlen(out);
124 }
125
126 /** Print data as integer, not as VALUE.
127  *
128  */
129 static ssize_t xlat_integer(UNUSED void *instance, REQUEST *request,
130                             char const *fmt, char *out, size_t outlen)
131 {
132         VALUE_PAIR      *vp;
133
134         uint64_t        int64 = 0;      /* Needs to be initialised to zero */
135         uint32_t        int32 = 0;      /* Needs to be initialised to zero */
136
137         while (isspace((int) *fmt)) fmt++;
138
139         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
140                 *out = '\0';
141                 return 0;
142         }
143
144         switch (vp->da->type) {
145         case PW_TYPE_OCTETS:
146         case PW_TYPE_STRING:
147                 if (vp->length > 8) {
148                         break;
149                 }
150
151                 if (vp->length > 4) {
152                         memcpy(&int64, vp->vp_octets, vp->length);
153                         return snprintf(out, outlen, "%" PRIu64, htonll(int64));
154                 }
155
156                 memcpy(&int32, vp->vp_octets, vp->length);
157                 return snprintf(out, outlen, "%i", htonl(int32));
158
159         case PW_TYPE_INTEGER64:
160                 return snprintf(out, outlen, "%" PRIu64, vp->vp_integer64);
161
162         /*
163          *      IP addresses are treated specially, as parsing functions assume the value
164          *      is bigendian and will convert it for us.
165          */
166         case PW_TYPE_IPV4_ADDR:
167                 return snprintf(out, outlen, "%u", htonl(vp->vp_ipaddr));
168
169         case PW_TYPE_IPV4_PREFIX:
170                 return snprintf(out, outlen, "%u", htonl((*(uint32_t *)(vp->vp_ipv4prefix + 2))));
171
172         case PW_TYPE_INTEGER:
173         case PW_TYPE_DATE:
174                 return snprintf(out, outlen, "%u", vp->vp_integer);
175         case PW_TYPE_BYTE:
176                 return snprintf(out, outlen, "%u", (unsigned int) vp->vp_byte);
177         case PW_TYPE_SHORT:
178                 return snprintf(out, outlen, "%u", (unsigned int) vp->vp_short);
179
180         /*
181          *      Ethernet is weird... It's network related, so we assume to it should be
182          *      bigendian.
183          */
184         case PW_TYPE_ETHERNET:
185                 memcpy(&int64, &vp->vp_ether, vp->length);
186                 return snprintf(out, outlen, "%" PRIu64, htonll(int64));
187
188         case PW_TYPE_SIGNED:
189                 return snprintf(out, outlen, "%i", vp->vp_signed);
190
191         case PW_TYPE_IPV6_ADDR:
192                 return fr_prints_uint128(out, outlen, ntohlll(*(uint128_t const *) &vp->vp_ipv6addr));
193
194         case PW_TYPE_IPV6_PREFIX:
195                 return fr_prints_uint128(out, outlen, ntohlll(*(uint128_t const *) &(vp->vp_ipv6prefix[2])));
196
197         default:
198                 break;
199         }
200
201         REDEBUG("Type '%s' of length %zu cannot be converted to integer",
202                 fr_int2str(dict_attr_types, vp->da->type, "???"), vp->length);
203         *out = '\0';
204
205         return -1;
206 }
207
208 /** Print data as hex, not as VALUE.
209  *
210  */
211 static ssize_t xlat_hex(UNUSED void *instance, REQUEST *request,
212                         char const *fmt, char *out, size_t outlen)
213 {
214         size_t i;
215         VALUE_PAIR *vp;
216         uint8_t const *p;
217         ssize_t ret;
218         size_t  len;
219
220         while (isspace((int) *fmt)) fmt++;
221
222         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
223                 *out = '\0';
224                 return -1;
225         }
226
227         ret = rad_vp2data(&p, vp);
228         if (ret < 0) {
229                 return ret;
230         }
231         len = (size_t) ret;
232
233         /*
234          *      Don't truncate the data.
235          */
236         if ((ret < 0 ) || (outlen < (len * 2))) {
237                 *out = 0;
238                 return 0;
239         }
240
241         for (i = 0; i < len; i++) {
242                 snprintf(out + 2*i, 3, "%02x", p[i]);
243         }
244
245         return len * 2;
246 }
247
248 /** Return the tag of an attribute reference
249  *
250  */
251 static ssize_t xlat_tag(UNUSED void *instance, REQUEST *request,
252                         char const *fmt, char *out, size_t outlen)
253 {
254         VALUE_PAIR *vp;
255
256         while (isspace((int) *fmt)) fmt++;
257
258         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
259                 *out = '\0';
260                 return 0;
261         }
262
263         if (!vp->da->flags.has_tag || !TAG_VALID(vp->tag)) {
264                 *out = '\0';
265                 return 0;
266         }
267
268         return snprintf(out, outlen, "%u", vp->tag);
269 }
270
271 /** Print out attribute info
272  *
273  * Prints out all instances of a current attribute, or all attributes in a list.
274  *
275  * At higher debugging levels, also prints out alternative decodings of the same
276  * value. This is helpful to determine types for unknown attributes of long
277  * passed vendors, or just crazy/broken NAS.
278  *
279  * It's also useful for exposing issues in the packet decoding functions, as in
280  * some cases they get fed random garbage data.
281  *
282  * This expands to a zero length string.
283  */
284 static ssize_t xlat_debug_attr(UNUSED void *instance, REQUEST *request, char const *fmt,
285                                char *out, UNUSED size_t outlen)
286 {
287         VALUE_PAIR *vp, **vps;
288         REQUEST *current;
289         vp_cursor_t cursor;
290         char buffer[1024];
291
292         value_pair_tmpl_t vpt;
293
294         if (!RDEBUG_ENABLED2) {
295                 *out = '\0';
296                 return -1;
297         }
298
299         while (isspace((int) *fmt)) fmt++;
300
301         if (tmpl_from_attr_str(&vpt, fmt, REQUEST_CURRENT, PAIR_LIST_REQUEST) <= 0) {
302                 RDEBUG("%s", fr_strerror());
303                 return -1;
304         }
305
306         current = request;
307         if (radius_request(&current, vpt.tmpl_request) < 0) return -2;
308
309         vps = radius_list(current, vpt.tmpl_list);
310         if (!vps) {
311                 return -2;
312         }
313
314         RIDEBUG("Attributes matching \"%s\"", fmt);
315         vp = fr_cursor_init(&cursor, vps);
316
317         if (vpt.tmpl_da) {
318                 vp = fr_cursor_next_by_da(&cursor, vpt.tmpl_da, TAG_ANY);
319         }
320         while (vp) {
321                 DICT_ATTR *dac = NULL;
322                 DICT_VENDOR *dv;
323
324                 vp_prints_value(buffer, sizeof(buffer), vp, '\'');
325
326                 if (vp->da->flags.has_tag) {
327                         RIDEBUG2("\t%s:%s:%i %s %s",
328                                 fr_int2str(pair_lists, vpt.tmpl_list, "<INVALID>"),
329                                 vp->da->name,
330                                 vp->tag,
331                                 fr_int2str(fr_tokens, vp->op, "<INVALID>"),
332                                 buffer);
333                 } else {
334                         RIDEBUG2("\t%s:%s %s %s",
335                                 fr_int2str(pair_lists, vpt.tmpl_list, "<INVALID>"),
336                                 vp->da->name,
337                                 fr_int2str(fr_tokens, vp->op, "<INVALID>"),
338                                 buffer);
339                 }
340
341                 if (!RDEBUG_ENABLED3) {
342                         goto next_vp;
343                 }
344
345                 if (vp->da->vendor) {
346                         dv = dict_vendorbyvalue(vp->da->vendor);
347                         RDEBUG3("\t\tvendor        : %i (%s)", vp->da->vendor, dv ? dv->name : "unknown");
348                 }
349                 RDEBUG3("\t\ttype          : %s", fr_int2str(dict_attr_types, vp->da->type, "<INVALID>"));
350                 RDEBUG3("\t\tlength        : %zu", vp->length);
351
352                 dac = talloc_memdup(request, vp->da, sizeof(DICT_ATTR));
353                 if (!dac) return -1;
354                 talloc_set_type(dac, DICT_ATTR);
355
356         next_vp:
357                 talloc_free(dac);
358
359                 if (vpt.tmpl_da) {
360                         vp = fr_cursor_next_by_da(&cursor, vpt.tmpl_da, TAG_ANY);
361                 } else {
362                         vp = fr_cursor_next(&cursor);
363                 }
364         }
365
366         *out = '\0';
367         return 0;
368 }
369
370 /** Prints the current module processing the request
371  *
372  */
373 static ssize_t xlat_module(UNUSED void *instance, REQUEST *request,
374                            UNUSED char const *fmt, char *out, size_t outlen)
375 {
376         strlcpy(out, request->module, outlen);
377
378         return strlen(out);
379 }
380
381 #ifdef WITH_UNLANG
382 /** Implements the Foreach-Variable-X
383  *
384  * @see modcall()
385  */
386 static ssize_t xlat_foreach(void *instance, REQUEST *request,
387                             UNUSED char const *fmt, char *out, size_t outlen)
388 {
389         VALUE_PAIR      **pvp;
390         size_t          len;
391
392         /*
393          *      See modcall, "FOREACH" for how this works.
394          */
395         pvp = (VALUE_PAIR **) request_data_reference(request, radius_get_vp, *(int*) instance);
396         if (!pvp || !*pvp) {
397                 *out = '\0';
398                 return 0;
399         }
400
401         len = vp_prints_value(out, outlen, *pvp, 0);
402         if (is_truncated(len, outlen)) {
403                 RDEBUG("Insufficient buffer space to write foreach value");
404                 return -1;
405         }
406
407         return len;
408 }
409 #endif
410
411 /** Print data as string, if possible.
412  *
413  * If attribute "Foo" is defined as "octets" it will normally
414  * be printed as 0x0a0a0a. The xlat "%{string:Foo}" will instead
415  * expand to "\n\n\n"
416  */
417 static ssize_t xlat_string(UNUSED void *instance, REQUEST *request,
418                            char const *fmt, char *out, size_t outlen)
419 {
420         size_t len;
421         ssize_t ret;
422         VALUE_PAIR *vp;
423         uint8_t const *p;
424
425         while (isspace((int) *fmt)) fmt++;
426
427         if (outlen < 3) {
428         nothing:
429                 *out = '\0';
430                 return 0;
431         }
432
433         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) goto nothing;
434
435         ret = rad_vp2data(&p, vp);
436         if (ret < 0) {
437                 return ret;
438         }
439
440         switch (vp->da->type) {
441         case PW_TYPE_OCTETS:
442                 len = fr_print_string((char const *) p, vp->length, out, outlen, '\0');
443                 break;
444
445         case PW_TYPE_STRING:
446                 len = strlcpy(out, vp->vp_strvalue, outlen);
447                 break;
448
449         default:
450                 len = fr_print_string((char const *) p, ret, out, outlen, '\0');
451                 break;
452         }
453
454         return len;
455 }
456
457 /** xlat expand string attribute value
458  *
459  */
460 static ssize_t xlat_xlat(UNUSED void *instance, REQUEST *request,
461                         char const *fmt, char *out, size_t outlen)
462 {
463         VALUE_PAIR *vp;
464
465         while (isspace((int) *fmt)) fmt++;
466
467         if (outlen < 3) {
468         nothing:
469                 *out = '\0';
470                 return 0;
471         }
472
473         if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) goto nothing;
474
475         return radius_xlat(out, outlen, request, vp->vp_strvalue, NULL, NULL);
476 }
477
478 /** Dynamically change the debugging level for the current request
479  *
480  * Example %{debug:3}
481  */
482 static ssize_t xlat_debug(UNUSED void *instance, REQUEST *request,
483                           char const *fmt, char *out, size_t outlen)
484 {
485         int level = 0;
486
487         /*
488          *  Expand to previous (or current) level
489          */
490         snprintf(out, outlen, "%d", request->log.lvl & RAD_REQUEST_OPTION_DEBUG4);
491
492         /*
493          *  Assume we just want to get the current value and NOT set it to 0
494          */
495         if (!*fmt)
496                 goto done;
497
498         level = atoi(fmt);
499         if (level == 0) {
500                 request->log.lvl = RAD_REQUEST_OPTION_NONE;
501                 request->log.func = NULL;
502         } else {
503                 if (level > 4) level = 4;
504
505                 request->log.lvl = level;
506                 request->log.func = vradlog_request;
507         }
508
509         done:
510         return strlen(out);
511 }
512
513 /*
514  *      Compare two xlat_t structs, based ONLY on the module name.
515  */
516 static int xlat_cmp(void const *one, void const *two)
517 {
518         xlat_t const *a = one;
519         xlat_t const *b = two;
520
521         if (a->length != b->length) {
522                 return a->length - b->length;
523         }
524
525         return memcmp(a->name, b->name, a->length);
526 }
527
528
529 /*
530  *      find the appropriate registered xlat function.
531  */
532 static xlat_t *xlat_find(char const *name)
533 {
534         xlat_t my_xlat;
535
536         strlcpy(my_xlat.name, name, sizeof(my_xlat.name));
537         my_xlat.length = strlen(my_xlat.name);
538
539         return rbtree_finddata(xlat_root, &my_xlat);
540 }
541
542
543 /** Register an xlat function.
544  *
545  * @param[in] name xlat name.
546  * @param[in] func xlat function to be called.
547  * @param[in] escape function to sanitize any sub expansions passed to the xlat function.
548  * @param[in] instance of module that's registering the xlat function.
549  * @return 0 on success, -1 on failure
550  */
551 int xlat_register(char const *name, RAD_XLAT_FUNC func, RADIUS_ESCAPE_STRING escape, void *instance)
552 {
553         xlat_t   *c;
554         xlat_t   my_xlat;
555         rbnode_t *node;
556
557         if (!name || !*name) {
558                 DEBUG("xlat_register: Invalid xlat name");
559                 return -1;
560         }
561
562         /*
563          *      First time around, build up the tree...
564          *
565          *      FIXME: This code should be hoisted out of this function,
566          *      and into a global "initialization".  But it isn't critical...
567          */
568         if (!xlat_root) {
569 #ifdef WITH_UNLANG
570                 int i;
571 #endif
572
573                 xlat_root = rbtree_create(NULL, xlat_cmp, free, 0);
574                 if (!xlat_root) {
575                         DEBUG("xlat_register: Failed to create tree");
576                         return -1;
577                 }
578
579 #ifdef WITH_UNLANG
580                 for (i = 0; xlat_foreach_names[i] != NULL; i++) {
581                         xlat_register(xlat_foreach_names[i],
582                                       xlat_foreach, NULL, &xlat_inst[i]);
583                         c = xlat_find(xlat_foreach_names[i]);
584                         rad_assert(c != NULL);
585                         c->internal = true;
586                 }
587 #endif
588
589 #define XLAT_REGISTER(_x) xlat_register(STRINGIFY(_x), xlat_ ## _x, NULL, NULL); \
590                 c = xlat_find(STRINGIFY(_x)); \
591                 rad_assert(c != NULL); \
592                 c->internal = true
593
594                 XLAT_REGISTER(integer);
595                 XLAT_REGISTER(strlen);
596                 XLAT_REGISTER(length);
597                 XLAT_REGISTER(hex);
598                 XLAT_REGISTER(tag);
599                 XLAT_REGISTER(string);
600                 XLAT_REGISTER(xlat);
601                 XLAT_REGISTER(module);
602                 XLAT_REGISTER(debug_attr);
603
604                 xlat_register("debug", xlat_debug, NULL, &xlat_inst[0]);
605                 c = xlat_find("debug");
606                 rad_assert(c != NULL);
607                 c->internal = true;
608         }
609
610         /*
611          *      If it already exists, replace the instance.
612          */
613         strlcpy(my_xlat.name, name, sizeof(my_xlat.name));
614         my_xlat.length = strlen(my_xlat.name);
615         c = rbtree_finddata(xlat_root, &my_xlat);
616         if (c) {
617                 if (c->internal) {
618                         DEBUG("xlat_register: Cannot re-define internal xlat");
619                         return -1;
620                 }
621
622                 c->func = func;
623                 c->escape = escape;
624                 c->instance = instance;
625                 return 0;
626         }
627
628         /*
629          *      Doesn't exist.  Create it.
630          */
631         c = rad_malloc(sizeof(*c));
632         memset(c, 0, sizeof(*c));
633
634         c->func = func;
635         c->escape = escape;
636         strlcpy(c->name, name, sizeof(c->name));
637         c->length = strlen(c->name);
638         c->instance = instance;
639
640         node = rbtree_insert_node(xlat_root, c);
641         if (!node) {
642                 talloc_free(c);
643                 return -1;
644         }
645
646         return 0;
647 }
648
649 /** Unregister an xlat function
650  *
651  * We can only have one function to call per name, so the passing of "func"
652  * here is extraneous.
653  *
654  * @param[in] name xlat to unregister.
655  * @param[in] func unused.
656  * @param[in] instance data.
657  */
658 void xlat_unregister(char const *name, UNUSED RAD_XLAT_FUNC func, void *instance)
659 {
660         xlat_t  *c;
661         xlat_t          my_xlat;
662
663         if (!name) return;
664
665         strlcpy(my_xlat.name, name, sizeof(my_xlat.name));
666         my_xlat.length = strlen(my_xlat.name);
667
668         c = rbtree_finddata(xlat_root, &my_xlat);
669         if (!c) return;
670
671         if (c->instance != instance) return;
672
673         rbtree_deletebydata(xlat_root, c);
674 }
675
676
677 /** Crappy temporary function to add attribute ref support to xlats
678  *
679  * This needs to die, and hopefully will die, when xlat functions accept
680  * xlat node structures.
681  *
682  * Provides either a pointer to a buffer which contains the value of the reference VALUE_PAIR
683  * in an architecture independent format. Or a pointer to the start of the fmt string.
684  *
685  * The pointer is only guaranteed to be valid between calls to xlat_fmt_to_ref,
686  * and so long as the source VALUE_PAIR is not freed.
687  *
688  * @param out where to write a pointer to the buffer to the data the xlat function needs to work on.
689  * @param request current request.
690  * @param fmt string.
691  * @returns the length of the data or -1 on error.
692  */
693 ssize_t xlat_fmt_to_ref(uint8_t const **out, REQUEST *request, char const *fmt)
694 {
695         VALUE_PAIR *vp;
696
697         while (isspace((int) *fmt)) fmt++;
698
699         if (fmt[0] == '&') {
700                 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
701                         *out = NULL;
702                         return -1;
703                 }
704
705                 return rad_vp2data(out, vp);
706         }
707
708         *out = (uint8_t const *)fmt;
709         return strlen(fmt);
710 }
711
712 /** De-register all xlat functions, used mainly for debugging.
713  *
714  */
715 void xlat_free(void)
716 {
717         rbtree_free(xlat_root);
718 }
719
720
721 #ifdef DEBUG_XLAT
722 #define XLAT_DEBUG DEBUG3
723 #else
724 #define XLAT_DEBUG(...)
725 #endif
726
727 static ssize_t xlat_tokenize_expansion(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
728                                        char const **error);
729 static ssize_t xlat_tokenize_literal(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
730                                      int brace, char const **error);
731 static size_t xlat_process(char **out, REQUEST *request, xlat_exp_t const * const head,
732                            RADIUS_ESCAPE_STRING escape, void *escape_ctx);
733
734 static ssize_t xlat_tokenize_alternation(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
735                                          char const **error)
736 {
737         ssize_t slen;
738         char *p;
739         xlat_exp_t *node;
740
741         rad_assert(fmt[0] == '%');
742         rad_assert(fmt[1] == '{');
743         rad_assert(fmt[2] == '%');
744         rad_assert(fmt[3] == '{');
745
746         XLAT_DEBUG("ALTERNATE <-- %s", fmt);
747
748         node = talloc_zero(ctx, xlat_exp_t);
749         node->type = XLAT_ALTERNATE;
750
751         p = fmt + 2;
752         slen = xlat_tokenize_expansion(node, p, &node->child, error);
753         if (slen <= 0) {
754                 talloc_free(node);
755                 return slen - (p - fmt);
756         }
757         p += slen;
758
759         if (p[0] != ':') {
760                 talloc_free(node);
761                 *error = "Expected ':' after first expansion";
762                 return -(p - fmt);
763         }
764         p++;
765
766         if (p[0] != '-') {
767                 talloc_free(node);
768                 *error = "Expected '-' after ':'";
769                 return -(p - fmt);
770         }
771         p++;
772
773         /*
774          *      Allow the RHS to be empty as a special case.
775          */
776         if (*p == '}') {
777                 /*
778                  *      Hack up an empty string.
779                  */
780                 node->alternate = talloc_zero(node, xlat_exp_t);
781                 node->alternate->type = XLAT_LITERAL;
782                 node->alternate->fmt = talloc_typed_strdup(node->alternate, "");
783                 *(p++) = '\0';
784
785         } else {
786                 slen = xlat_tokenize_literal(node, p,  &node->alternate, true, error);
787                 if (slen <= 0) {
788                         talloc_free(node);
789                         return slen - (p - fmt);
790                 }
791
792                 if (!node->alternate) {
793                         talloc_free(node);
794                         *error = "Empty expansion is invalid";
795                         return -(p - fmt);
796                 }
797                 p += slen;
798         }
799
800         *head = node;
801         return p - fmt;
802 }
803
804 static ssize_t xlat_tokenize_expansion(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
805                                        char const **error)
806 {
807         ssize_t slen;
808         char *p, *q, *brace;
809         char const *attrname;
810         xlat_exp_t *node;
811
812         rad_assert(fmt[0] == '%');
813         rad_assert(fmt[1] == '{');
814
815         /*
816          *      %{%{...}:-bar}
817          */
818         if ((fmt[2] == '%') && (fmt[3] == '{')) {
819                 return xlat_tokenize_alternation(ctx, fmt, head, error);
820         }
821
822         XLAT_DEBUG("EXPANSION <-- %s", fmt);
823         node = talloc_zero(ctx, xlat_exp_t);
824         attrname = node->fmt = fmt + 2;
825         node->len = 0;
826
827 #ifdef HAVE_REGEX
828         /*
829          *      Handle regex's specially.
830          */
831         if (isdigit((int) fmt[2]) && (fmt[3] == '}')) {
832                 if (fmt[2] == '9') {
833                         talloc_free(node);
834                         *error = "Invalid regex reference";
835                         return -2;
836                 }
837
838                 XLAT_DEBUG("REGEX <-- %s", fmt);
839                 fmt[3] = '\0';
840                 node->attr.tmpl_num = fmt[2] - '0'; /* ASCII */
841
842                 node->type = XLAT_REGEX;
843                 *head = node;
844                 return 4;
845         }
846 #endif /* HAVE_REGEX */
847
848         /*
849          *      %{Attr-Name}
850          *      %{Attr-Name[#]}
851          *      %{Tunnel-Password:1}
852          *      %{Tunnel-Password:1[#]}
853          *      %{request:Attr-Name}
854          *      %{request:Tunnel-Password:1}
855          *      %{request:Tunnel-Password:1[#]}
856          *      %{mod:foo}
857          */
858          brace = NULL;
859         for (p = fmt + 2; *p != '\0'; p++) {
860                 if (*p == ':') break;
861
862                 if (isspace((int) *p)) break;
863
864                 if (*p == '[') break;
865
866                 if (*p == '}') break;
867         }
868
869         if (*p != ':') p = NULL;
870
871         /*
872          *      Might be a module name reference.
873          */
874         if (p) {
875                 *p = '\0';
876
877                 /*
878                  *      %{mod:foo}
879                  */
880                 node->xlat = xlat_find(node->fmt);
881                 if (node->xlat) {
882                         node->type = XLAT_MODULE;
883
884                         XLAT_DEBUG("MOD <-- %s ... %s", node->fmt, p + 1);
885
886                         slen = xlat_tokenize_literal(node, p + 1, &node->child, true, error);
887                         if (slen <= 0) {
888                                 talloc_free(node);
889                                 return slen - (p - fmt);
890                         }
891                         p += slen + 1;
892
893                         *head = node;
894                         rad_assert(node->next == NULL);
895                         return p - fmt;
896                 }
897
898                 /*
899                  *      Modules can have '}' in their RHS, so we
900                  *      didn't check for that until now.
901                  *
902                  *      As of now, node->fmt MUST be a reference to an
903                  *      attribute, however complicated.  So it MUST have a closing brace.
904                  */
905                 brace = strchr(p + 1, '}');
906                 if (!brace) goto no_brace;
907                 *brace = '\0';
908
909                 /*
910                  *      %{User-Name}
911                  *      %{User-Name[1]}
912                  *      %{Tunnel-Password:1}
913                  *      %{request:Tunnel-Password:1}
914                  *
915                  *      <sigh>  The syntax is fairly poor.
916                  */
917                 XLAT_DEBUG("Looking for list in '%s'", attrname);
918
919                 /*
920                  *      Not a module.  Has to be an attribute
921                  *      reference.
922                  *
923                  *      As of v3, we've removed %{request: ..>} as
924                  *      internally registered xlats.
925                  */
926                 *p = ':';
927                 node->attr.tmpl_request = radius_request_name(&attrname, REQUEST_CURRENT);
928                 rad_assert(node->attr.tmpl_request != REQUEST_UNKNOWN);
929
930                 node->attr.tmpl_list = radius_list_name(&attrname, PAIR_LIST_REQUEST);
931                 if (node->attr.tmpl_list == PAIR_LIST_UNKNOWN) {
932                         talloc_free(node);
933                         *error = "Unknown module";
934                         return -2;
935                 }
936
937                 /*
938                  *      Check for a trailing tag.
939                  */
940                 p = strchr(attrname, ':');
941                 if (p) *p = '\0';
942
943         } else {
944                 brace = strchr(attrname, '}');
945                 if (!brace) {
946                 no_brace:
947                         talloc_free(node);
948                         *error = "No matching closing brace";
949                         return -1;      /* second character of format string */
950                 }
951                 *brace = '\0';
952
953                 node->attr.tmpl_request = REQUEST_CURRENT;
954                 node->attr.tmpl_list = PAIR_LIST_REQUEST;
955         }
956
957         *brace = '\0';
958
959         XLAT_DEBUG("Looking for attribute name in %s", attrname);
960
961         /*
962          *      Allow for an array reference.  They come AFTER the
963          *      tag, if the tag exists.  Otherwise, they come after
964          *      the attribute name.
965          */
966         if (p) {
967                 q = strchr(p + 1, '[');
968         } else {
969                 q = strchr(attrname, '[');
970         }
971         if (q) *(q++) = '\0';
972
973         if (!*attrname) {
974                 talloc_free(node);
975                 *error = "Empty expression is invalid";
976                 return -(attrname - fmt);
977         }
978
979         /*
980          *      It's either an attribute name, or a Tunnel-Password:TAG
981          *      with the ':' already set to NULL.
982          */
983         node->attr.tmpl_da = dict_attrbyname(attrname);
984         if (!node->attr.tmpl_da) {
985                 /*
986                  *      Foreach.  Maybe other stuff, too.
987                  */
988                 node->xlat = xlat_find(attrname);
989                 if (node->xlat) {
990                         node->type = XLAT_VIRTUAL;
991                         node->fmt = attrname;
992
993                         XLAT_DEBUG("VIRTUAL <-- %s", node->fmt);
994                         *head = node;
995                         rad_assert(node->next == NULL);
996                         brace++;
997                         return brace - fmt;
998                 }
999
1000                 talloc_free(node);
1001                 *error = "Unknown attribute";
1002                 return -(attrname - fmt);
1003         }
1004
1005         /*
1006          *      Parse the tag.
1007          */
1008         if (p) {
1009                 unsigned long tag;
1010                 char *end;
1011
1012                 if (!node->attr.tmpl_da->flags.has_tag) {
1013                         talloc_free(node);
1014                         *error = "Attribute cannot have a tag";
1015                         return - (p - fmt);
1016                 }
1017
1018                 tag = strtoul(p + 1, &end, 10);
1019                 p++;
1020
1021                 if (tag == ULONG_MAX) {
1022                         talloc_free(node);
1023                         *error = "Invalid tag value";
1024                         return - (p - fmt);
1025                 }
1026
1027                 node->attr.tmpl_tag = tag;
1028                 p = end;
1029
1030                 if (*p) {
1031                         talloc_free(node);
1032                         *error = "Unexpected text after tag";
1033                         return - (p - fmt);
1034                 }
1035
1036         } else {
1037                 node->attr.tmpl_tag = TAG_ANY;
1038                 /* leave p alone */
1039         }
1040
1041         /*
1042          *      Check for array reference
1043          */
1044         if (q) {
1045                 unsigned long num;
1046                 char *end;
1047
1048                 p = q;
1049                 if (*p== '#') {
1050                         node->attr.tmpl_num = NUM_COUNT;
1051                         p++;
1052
1053                 } else if (*p == '*') {
1054                         node->attr.tmpl_num = NUM_ALL;
1055                         p++;
1056
1057                 } else if (isdigit((int) *p)) {
1058                         num = strtoul(p, &end, 10);
1059                         if (num > 1000) {
1060                                 talloc_free(node);
1061                                 *error = "Invalid array index";
1062                                 return - (p - fmt);
1063                         }
1064                         p = end;
1065                         node->attr.tmpl_num = num;
1066
1067                 } else {
1068                         talloc_free(node);
1069                         *error = "Invalid array index";
1070                         return - (p - fmt);
1071                 }
1072
1073                 if (*p != ']') {
1074                         talloc_free(node);
1075                         *error = "Expected ']'";
1076                         return - (p - fmt);
1077                 }
1078
1079                 p++;
1080                 if (*p) {
1081                         talloc_free(node);
1082                         *error = "Unexpected text after array reference";
1083                         return - (p - fmt);
1084                 }
1085         } else {
1086                 node->attr.tmpl_num = NUM_ANY;
1087         }
1088
1089         rad_assert(!p || (p == brace));
1090
1091         node->type = XLAT_ATTRIBUTE;
1092         p = brace + 1;
1093
1094         *head = node;
1095         rad_assert(node->next == NULL);
1096         return p - fmt;
1097 }
1098
1099
1100 static ssize_t xlat_tokenize_literal(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1101                                      int brace, char const **error)
1102 {
1103         char *p, *q;
1104         xlat_exp_t *node;
1105
1106         if (!*fmt) return 0;
1107
1108         XLAT_DEBUG("LITERAL <-- %s", fmt);
1109
1110         node = talloc_zero(ctx, xlat_exp_t);
1111         node->fmt = fmt;
1112         node->len = 0;
1113         node->type = XLAT_LITERAL;
1114
1115         p = fmt;
1116         q = fmt;
1117
1118         while (*p) {
1119                 /*
1120                  *      Convert \n to it's literal representation.
1121                  */
1122                 if (p[0] == '\\') switch (p[1]) {
1123                 case 't':
1124                         *(q++) = '\t';
1125                         p += 2;
1126                         node->len++;
1127                         continue;
1128
1129                 case 'n':
1130                         *(q++) = '\n';
1131                         p += 2;
1132                         node->len++;
1133                         continue;
1134
1135                 case 'x':
1136                         p += 2;
1137                         if (!p[0] || !p[1]) {
1138                                 talloc_free(node);
1139                                 *error = "Hex expansion requires two hex digits";
1140                                 return -(p - fmt);
1141                         }
1142
1143                         if (!fr_hex2bin((uint8_t *) q, 1, p, 2)) {
1144                                 talloc_free(node);
1145                                 *error = "Invalid hex characters";
1146                                 return -(p - fmt);
1147                         }
1148
1149                         /*
1150                          *      Don't let people shoot themselves in the foot.
1151                          *      \x00 is forbidden.
1152                          */
1153                         if (!*q) {
1154                                 talloc_free(node);
1155                                 *error = "Cannot add zero byte to printable string";
1156                                 return -(p - fmt);
1157                         }
1158
1159                         p += 2;
1160                         q++;
1161                         node->len++;
1162                         continue;
1163
1164                 default:
1165                         *(q++) = *p;
1166                         p += 2;
1167                         node->len++;
1168                         continue;
1169                 }
1170
1171                 /*
1172                  *      Process the expansion.
1173                  */
1174                 if ((p[0] == '%') && (p[1] == '{')) {
1175                         ssize_t slen;
1176
1177                         XLAT_DEBUG("LITERAL <-- %s", node->fmt);
1178
1179                         slen = xlat_tokenize_expansion(node, p, &node->next, error);
1180                         if (slen <= 0) {
1181                                 talloc_free(node);
1182                                 return slen - (p - fmt);
1183                         }
1184                         *p = '\0'; /* end the literal */
1185                         p += slen;
1186
1187                         rad_assert(node->next != NULL);
1188
1189                         /*
1190                          *      Short-circuit the recursive call.
1191                          *      This saves another function call and
1192                          *      memory allocation.
1193                          */
1194                         if (!*p) break;
1195
1196                         /*
1197                          *      "foo %{User-Name} bar"
1198                          *      LITERAL         "foo "
1199                          *      EXPANSION       User-Name
1200                          *      LITERAL         " bar"
1201                          */
1202                         slen = xlat_tokenize_literal(node->next, p, &(node->next->next), brace, error);
1203                         rad_assert(slen != 0);
1204                         if (slen < 0) {
1205                                 talloc_free(node);
1206                                 return slen - (p - fmt);
1207                         }
1208
1209                         p += slen;
1210                         break;  /* stop processing the string */
1211                 }
1212
1213                 /*
1214                  *      Check for valid single-character expansions.
1215                  */
1216                 if (p[0] == '%') {
1217                         ssize_t slen;
1218                         xlat_exp_t *next;
1219
1220                         if (!p[1] || !strchr("%dlmtDGHISTYv", p[1])) {
1221                                         talloc_free(node);
1222                                         *error = "Invalid variable expansion";
1223                                         p++;
1224                                         return - (p - fmt);
1225                         }
1226
1227                         next = talloc_zero(node, xlat_exp_t);
1228                         next->len = 1;
1229
1230                         if (p[1] == '%') {
1231                                 next->fmt = talloc_typed_strdup(next, "%");
1232
1233                                 XLAT_DEBUG("LITERAL <-- %s", next->fmt);
1234                                 next->type = XLAT_LITERAL;
1235
1236                         } else {
1237                                 next->fmt = p + 1;
1238
1239                                 XLAT_DEBUG("PERCENT <-- %c", *next->fmt);
1240                                 next->type = XLAT_PERCENT;
1241                         }
1242
1243                         node->next = next;
1244                         *p = '\0';
1245                         p += 2;
1246
1247                         if (!*p) break;
1248
1249                         /*
1250                          *      And recurse.
1251                          */
1252                         slen = xlat_tokenize_literal(node->next, p, &(node->next->next), brace, error);
1253                         rad_assert(slen != 0);
1254                         if (slen < 0) {
1255                                 talloc_free(node);
1256                                 return slen - (p - fmt);
1257                         }
1258
1259                         p += slen;
1260                         break;  /* stop processing the string */
1261                 }
1262
1263                 /*
1264                  *      If required, eat the brace.
1265                  */
1266                 if (brace && (*p == '}')) {
1267                         *q = '\0';
1268                         p++;
1269                         break;
1270                 }
1271
1272                 *(q++) = *(p++);
1273                 node->len++;
1274         }
1275
1276         /*
1277          *      Squash zero-width literals
1278          */
1279         if (node->len > 0) {
1280                 *head = node;
1281         } else {
1282                 *head = talloc_steal(ctx, node->next);
1283                 talloc_free(node);
1284         }
1285
1286         return p - fmt;
1287 }
1288
1289
1290 static char const xlat_tabs[] = "                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ";
1291
1292 static void xlat_tokenize_debug(xlat_exp_t const *node, int lvl)
1293 {
1294         rad_assert(node != NULL);
1295
1296         if (lvl >= (int) sizeof(xlat_tabs)) lvl = sizeof(xlat_tabs);
1297
1298         while (node) {
1299                 switch (node->type) {
1300                 case XLAT_LITERAL:
1301                         DEBUG("%.*sliteral --> %s", lvl, xlat_tabs, node->fmt);
1302                         break;
1303
1304                 case XLAT_PERCENT:
1305                         DEBUG("%.*spercent --> %c", lvl, xlat_tabs, node->fmt[0]);
1306                         break;
1307
1308                 case XLAT_ATTRIBUTE:
1309                         rad_assert(node->attr.tmpl_da != NULL);
1310                         DEBUG("%.*sattribute --> %s", lvl, xlat_tabs, node->attr.tmpl_da->name);
1311                         rad_assert(node->child == NULL);
1312                         if ((node->attr.tmpl_tag != TAG_ANY) || (node->attr.tmpl_num != NUM_ANY)) {
1313                                 DEBUG("%.*s{", lvl, xlat_tabs);
1314
1315                                 DEBUG("%.*sref  %d", lvl + 1, xlat_tabs, node->attr.tmpl_request);
1316                                 DEBUG("%.*slist %d", lvl + 1, xlat_tabs, node->attr.tmpl_list);
1317
1318                                 if (node->attr.tmpl_tag != TAG_ANY) {
1319                                         DEBUG("%.*stag %d", lvl + 1, xlat_tabs, node->attr.tmpl_tag);
1320                                 }
1321                                 if (node->attr.tmpl_num != NUM_ANY) {
1322                                         if (node->attr.tmpl_num == NUM_COUNT) {
1323                                                 DEBUG("%.*s[#]", lvl + 1, xlat_tabs);
1324                                         } else if (node->attr.tmpl_num == NUM_ALL) {
1325                                                 DEBUG("%.*s[*]", lvl + 1, xlat_tabs);
1326                                         } else {
1327                                                 DEBUG("%.*s[%d]", lvl + 1, xlat_tabs, node->attr.tmpl_num);
1328                                         }
1329                                 }
1330
1331                                 DEBUG("%.*s}", lvl, xlat_tabs);
1332                         }
1333                         break;
1334
1335                 case XLAT_VIRTUAL:
1336                         rad_assert(node->fmt != NULL);
1337                         DEBUG("%.*svirtual --> %s", lvl, xlat_tabs, node->fmt);
1338                         break;
1339
1340                 case XLAT_MODULE:
1341                         rad_assert(node->xlat != NULL);
1342                         DEBUG("%.*sxlat --> %s", lvl, xlat_tabs, node->xlat->name);
1343                         if (node->child) {
1344                                 DEBUG("%.*s{", lvl, xlat_tabs);
1345                                 xlat_tokenize_debug(node->child, lvl + 1);
1346                                 DEBUG("%.*s}", lvl, xlat_tabs);
1347                         }
1348                         break;
1349
1350 #ifdef HAVE_REGEX
1351                 case XLAT_REGEX:
1352                         DEBUG("%.*sregex-var --> %d", lvl, xlat_tabs, node->attr.tmpl_num);
1353                         break;
1354 #endif
1355
1356                 case XLAT_ALTERNATE:
1357                         DEBUG("%.*sif {", lvl, xlat_tabs);
1358                         xlat_tokenize_debug(node->child, lvl + 1);
1359                         DEBUG("%.*s}", lvl, xlat_tabs);
1360                         DEBUG("%.*selse {", lvl, xlat_tabs);
1361                         xlat_tokenize_debug(node->alternate, lvl + 1);
1362                         DEBUG("%.*s}", lvl, xlat_tabs);
1363                         break;
1364                 }
1365                 node = node->next;
1366         }
1367 }
1368
1369 size_t xlat_sprint(char *buffer, size_t bufsize, xlat_exp_t const *node)
1370 {
1371         size_t len;
1372         char *p, *end;
1373
1374         if (!node) {
1375                 *buffer = '\0';
1376                 return 0;
1377         }
1378
1379         p = buffer;
1380         end = buffer + bufsize;
1381
1382         while (node) {
1383                 switch (node->type) {
1384                 case XLAT_LITERAL:
1385                         strlcpy(p, node->fmt, end - p);
1386                         p += strlen(p);
1387                         break;
1388
1389                 case XLAT_PERCENT:
1390                         p[0] = '%';
1391                         p[1] = node->fmt[0];
1392                         p += 2;
1393                         break;
1394
1395                 case XLAT_ATTRIBUTE:
1396                         *(p++) = '%';
1397                         *(p++) = '{';
1398
1399                         if (node->attr.tmpl_request != REQUEST_CURRENT) {
1400                                 strlcpy(p, fr_int2str(request_refs, node->attr.tmpl_request, "??"), end - p);
1401                                 p += strlen(p);
1402                                 *(p++) = '.';
1403                         }
1404
1405                         if ((node->attr.tmpl_request != REQUEST_CURRENT) ||
1406                             (node->attr.tmpl_list != PAIR_LIST_REQUEST)) {
1407                                 strlcpy(p, fr_int2str(pair_lists, node->attr.tmpl_list, "??"), end - p);
1408                                 p += strlen(p);
1409                                 *(p++) = ':';
1410                         }
1411
1412                         strlcpy(p, node->attr.tmpl_da->name, end - p);
1413                         p += strlen(p);
1414
1415                         if (node->attr.tmpl_tag != TAG_ANY) {
1416                                 *(p++) = ':';
1417                                 snprintf(p, end - p, "%u", node->attr.tmpl_tag);
1418                                 p += strlen(p);
1419                         }
1420
1421                         if (node->attr.tmpl_num != NUM_ANY) {
1422                                 *(p++) = '[';
1423                                 switch (node->attr.tmpl_num) {
1424                                 case NUM_COUNT:
1425                                         *(p++) = '#';
1426                                         break;
1427
1428                                 case NUM_ALL:
1429                                         *(p++) = '*';
1430                                         break;
1431
1432                                 default:
1433                                         snprintf(p, end - p, "%i", node->attr.tmpl_num);
1434                                         p += strlen(p);
1435                                 }
1436                                 *(p++) = ']';
1437                         }
1438                         *(p++) = '}';
1439                         break;
1440 #ifdef HAVE_REGEX
1441                 case XLAT_REGEX:
1442                         snprintf(p, end - p, "%%{%i}", node->attr.tmpl_num);
1443                         p += strlen(p);
1444                         break;
1445 #endif
1446                 case XLAT_VIRTUAL:
1447                         *(p++) = '%';
1448                         *(p++) = '{';
1449                         strlcpy(p, node->fmt, end - p);
1450                         p += strlen(p);
1451                         *(p++) = '}';
1452                         break;
1453
1454                 case XLAT_MODULE:
1455                         *(p++) = '%';
1456                         *(p++) = '{';
1457                         strlcpy(p, node->xlat->name, end - p);
1458                         p += strlen(p);
1459                         *(p++) = ':';
1460                         rad_assert(node->child != NULL);
1461                         len = xlat_sprint(p, end - p, node->child);
1462                         p += len;
1463                         *(p++) = '}';
1464                         break;
1465
1466                 case XLAT_ALTERNATE:
1467                         *(p++) = '%';
1468                         *(p++) = '{';
1469
1470                         len = xlat_sprint(p, end - p, node->child);
1471                         p += len;
1472
1473                         *(p++) = ':';
1474                         *(p++) = '-';
1475
1476                         len = xlat_sprint(p, end - p, node->alternate);
1477                         p += len;
1478
1479                         *(p++) = '}';
1480                         break;
1481                 }
1482
1483
1484                 if (p == end) break;
1485
1486                 node = node->next;
1487         }
1488
1489         *p = '\0';
1490
1491         return p - buffer;
1492 }
1493
1494 ssize_t xlat_tokenize(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1495                       char const **error)
1496 {
1497         return xlat_tokenize_literal(ctx, fmt, head, false, error);
1498 }
1499
1500
1501 /** Tokenize an xlat expansion
1502  *
1503  * @param[in] request the input request.  Memory will be attached here.
1504  * @param[in] fmt the format string to expand
1505  * @param[out] head the head of the xlat list / tree structure.
1506  */
1507 static ssize_t xlat_tokenize_request(REQUEST *request, char const *fmt, xlat_exp_t **head)
1508 {
1509         ssize_t slen;
1510         char *tokens;
1511         char const *error;
1512
1513         *head = NULL;
1514
1515         /*
1516          *      Copy the original format string to a buffer so that
1517          *      the later functions can mangle it in-place, which is
1518          *      much faster.
1519          */
1520         tokens = talloc_typed_strdup(request, fmt);
1521         if (!tokens) return -1;
1522
1523         slen = xlat_tokenize_literal(request, tokens, head, false, &error);
1524
1525         /*
1526          *      Zero length expansion, return a zero length node.
1527          */
1528         if (slen == 0) {
1529                 *head = talloc_zero(request, xlat_exp_t);
1530         }
1531
1532         /*
1533          *      Output something like:
1534          *
1535          *      "format string"
1536          *      "       ^ error was here"
1537          */
1538         if (slen < 0) {
1539                 talloc_free(tokens);
1540                 rad_assert(error != NULL);
1541
1542                 REMARKER(fmt, -slen, error);
1543                 return slen;
1544         }
1545
1546         if (*head && (debug_flag > 2)) {
1547                 DEBUG("%s", fmt);
1548                 DEBUG("Parsed xlat tree:");
1549                 xlat_tokenize_debug(*head, 0);
1550         }
1551
1552         /*
1553          *      All of the nodes point to offsets in the "tokens"
1554          *      string.  Let's ensure that free'ing head will free
1555          *      "tokens", too.
1556          */
1557         (void) talloc_steal(*head, tokens);
1558
1559         return slen;
1560 }
1561
1562
1563 static char *xlat_getvp(TALLOC_CTX *ctx, REQUEST *request, pair_lists_t list, DICT_ATTR const *da,
1564                         int8_t tag, int num, bool return_null)
1565 {
1566         VALUE_PAIR *vp, *vps = NULL, *myvp = NULL;
1567         RADIUS_PACKET *packet = NULL;
1568         DICT_VALUE *dv;
1569         char *ret = NULL;
1570
1571         /*
1572          *      Arg.  Too much abstraction is annoying.
1573          */
1574         switch (list) {
1575         default:
1576                 if (return_null) return NULL;
1577                 return vp_aprint_type(ctx, da->type);
1578
1579         case PAIR_LIST_CONTROL:
1580                 vps = request->config_items;
1581                 break;
1582
1583         case PAIR_LIST_REQUEST:
1584                 packet = request->packet;
1585                 if (packet) vps = packet->vps;
1586                 break;
1587
1588         case PAIR_LIST_REPLY:
1589                 packet = request->reply;
1590                 if (packet) vps = packet->vps;
1591                 break;
1592
1593 #ifdef WITH_PROXY
1594         case PAIR_LIST_PROXY_REQUEST:
1595                 packet = request->proxy;
1596                 if (packet) vps = packet->vps;
1597                 break;
1598
1599         case PAIR_LIST_PROXY_REPLY:
1600                 packet = request->proxy_reply;
1601                 if (packet) vps = packet->vps;
1602                 break;
1603 #endif
1604
1605 #ifdef WITH_COA
1606         case PAIR_LIST_COA:
1607         case PAIR_LIST_DM:
1608                 if (request->coa) packet = request->coa->packet;
1609                 if (packet) vps = packet->vps;
1610                 break;
1611
1612         case PAIR_LIST_COA_REPLY:
1613         case PAIR_LIST_DM_REPLY:
1614                 if (request->coa) packet = request->coa->reply;
1615                 if (packet) vps = packet->vps;
1616                 break;
1617
1618 #endif
1619         }
1620
1621         /*
1622          *      Now we have the list, check to see if we have an attribute in
1623          *      the request, if we do, it takes precedence over the virtual
1624          *      attributes.
1625          *
1626          *      This allows users to manipulate virtual attributes as if they
1627          *      were real ones.
1628          */
1629         vp = pairfind(vps, da->attr, da->vendor, tag);
1630         if (vp) goto do_print;
1631
1632         /*
1633          *      We didn't find the VP in a list.  It MIGHT be a
1634          *      virtual one, in which case we do lots more checks
1635          *      below.  However, if we're looking for a normal
1636          *      attribute, it must exist, and therefore not finding it
1637          *      means we return NULL.
1638          */
1639         if (!da->flags.virtual) return NULL;
1640
1641         /*
1642          *      Some non-packet expansions
1643          */
1644         switch (da->attr) {
1645         default:
1646                 break;          /* ignore them */
1647
1648         case PW_CLIENT_SHORTNAME:
1649                 if (num == NUM_COUNT) goto count;
1650                 if (request->client && request->client->shortname) {
1651                         return talloc_typed_strdup(ctx, request->client->shortname);
1652                 }
1653                 return talloc_typed_strdup(ctx, "<UNKNOWN-CLIENT>");
1654
1655         case PW_REQUEST_PROCESSING_STAGE:
1656                 if (num == NUM_COUNT) goto count;
1657                 if (request->component) {
1658                         return talloc_typed_strdup(ctx, request->component);
1659                 }
1660                 return talloc_typed_strdup(ctx, "server_core");
1661
1662         case PW_VIRTUAL_SERVER:
1663                 if (num == NUM_COUNT) goto count;
1664                 if (!request->server) return NULL;
1665                 return talloc_typed_strdup(ctx, request->server);
1666
1667         case PW_MODULE_RETURN_CODE:
1668                 if (num == NUM_COUNT) goto count;
1669                 if (!request->rcode) return NULL;
1670                 return talloc_typed_strdup(ctx, fr_int2str(modreturn_table, request->rcode, ""));
1671         }
1672
1673         /*
1674          *      All of the attributes must now refer to a packet.
1675          *      If there's no packet, we can't print any attribute
1676          *      referencing it.
1677          */
1678         if (!packet) {
1679                 if (return_null) return NULL;
1680                 return vp_aprint_type(ctx, da->type);
1681         }
1682
1683         vp = NULL;
1684         switch (da->attr) {
1685         default:
1686                 break;
1687
1688         case PW_PACKET_TYPE:
1689                 dv = dict_valbyattr(PW_PACKET_TYPE, 0, packet->code);
1690                 if (dv) return talloc_typed_strdup(ctx, dv->name);
1691                 return talloc_typed_asprintf(ctx, "%d", packet->code);
1692
1693         case PW_RESPONSE_PACKET_TYPE:
1694         {
1695                 int code = 0;
1696
1697 #ifdef WITH_PROXY
1698                 if (request->proxy_reply && (!request->reply || !request->reply->code)) {
1699                         code = request->proxy_reply->code;
1700                 } else
1701 #endif
1702                         if (request->reply) {
1703                                 code = request->reply->code;
1704                         }
1705
1706                 return talloc_typed_strdup(ctx, fr_packet_codes[code]);
1707         }
1708
1709         /*
1710          *      Virtual attributes which require a temporary VALUE_PAIR
1711          *      to be allocated. We can't use stack allocated memory
1712          *      because of the talloc checks sprinkled throughout the
1713          *      various VP functions.
1714          */
1715         case PW_PACKET_AUTHENTICATION_VECTOR:
1716                 myvp = pairalloc(ctx, da);
1717                 pairmemcpy(myvp, packet->vector, sizeof(packet->vector));
1718                 vp = myvp;
1719                 break;
1720
1721         case PW_CLIENT_IP_ADDRESS:
1722         case PW_PACKET_SRC_IP_ADDRESS:
1723                 if (packet->src_ipaddr.af == AF_INET) {
1724                         myvp = pairalloc(ctx, da);
1725                         myvp->vp_ipaddr = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
1726                         vp = myvp;
1727                 }
1728                 break;
1729
1730         case PW_PACKET_DST_IP_ADDRESS:
1731                 if (packet->dst_ipaddr.af == AF_INET) {
1732                         myvp = pairalloc(ctx, da);
1733                         myvp->vp_ipaddr = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
1734                         vp = myvp;
1735                 }
1736                 break;
1737
1738         case PW_PACKET_SRC_IPV6_ADDRESS:
1739                 if (packet->src_ipaddr.af == AF_INET6) {
1740                         myvp = pairalloc(ctx, da);
1741                         memcpy(&myvp->vp_ipv6addr,
1742                                &packet->src_ipaddr.ipaddr.ip6addr,
1743                                sizeof(packet->src_ipaddr.ipaddr.ip6addr));
1744                         vp = myvp;
1745                 }
1746                 break;
1747
1748         case PW_PACKET_DST_IPV6_ADDRESS:
1749                 if (packet->dst_ipaddr.af == AF_INET6) {
1750                         myvp = pairalloc(ctx, da);
1751                         memcpy(&myvp->vp_ipv6addr,
1752                                &packet->dst_ipaddr.ipaddr.ip6addr,
1753                                sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
1754                         vp = myvp;
1755                 }
1756                 break;
1757
1758         case PW_PACKET_SRC_PORT:
1759                 myvp = pairalloc(ctx, da);
1760                 myvp->vp_integer = packet->src_port;
1761                 vp = myvp;
1762                 break;
1763
1764         case PW_PACKET_DST_PORT:
1765                 myvp = pairalloc(ctx, da);
1766                 myvp->vp_integer = packet->dst_port;
1767                 vp = myvp;
1768                 break;
1769         }
1770
1771         /*
1772          *      Fake various operations for virtual attributes.
1773          */
1774         if (myvp) {
1775                 if (num != NUM_ANY) switch (num) {
1776                 /*
1777                  *      [n] is NULL (we only have [0])
1778                  */
1779                 default:
1780                         goto finish;
1781                 /*
1782                  *      [*] means only one.
1783                  */
1784                 case NUM_ALL:
1785                         break;
1786
1787                 /*
1788                  *      [#] means 1 (as there's only one)
1789                  */
1790                 case NUM_COUNT:
1791                 count:
1792                         ret = talloc_strdup(ctx, "1");
1793                         goto finish;
1794
1795                 /*
1796                  *      [0] is fine (get the first instance)
1797                  */
1798                 case 0:
1799                         break;
1800                 }
1801                 goto print;
1802         }
1803
1804 do_print:
1805         /*
1806          *      We want the N'th VP.
1807          */
1808         if (num != NUM_ANY) {
1809                 int count = 0;
1810                 vp_cursor_t cursor;
1811
1812                 switch (num) {
1813                 /*
1814                  *      Return a count of the VPs.
1815                  */
1816                 case NUM_COUNT:
1817                         fr_cursor_init(&cursor, &vp);
1818                         while (fr_cursor_next_by_da(&cursor, da, tag) != NULL) {
1819                                 count++;
1820                         }
1821                         return talloc_typed_asprintf(ctx, "%d", count);
1822
1823                 /*
1824                  *      Ugly, but working.
1825                  */
1826                 case NUM_ALL:
1827                 {
1828                         char *p, *q;
1829
1830                         (void) fr_cursor_init(&cursor, &vp);
1831                         vp = fr_cursor_next_by_da(&cursor, da, tag);
1832                         if (!vp) return NULL;
1833
1834                         p = vp_aprint_value(ctx, vp, '"');
1835                         if (!p) return NULL;
1836                         while ((vp = fr_cursor_next_by_da(&cursor, da, tag)) != NULL) {
1837                                 q = vp_aprint_value(ctx, vp, '"');
1838                                 if (!q) return NULL;
1839                                 p = talloc_strdup_append(p, ",");
1840                                 p = talloc_strdup_append(p, q);
1841                         }
1842
1843                         return p;
1844                 }
1845
1846                 default:
1847                         fr_cursor_init(&cursor, &vp);
1848                         while ((vp = fr_cursor_next_by_da(&cursor, da, tag)) != NULL) {
1849                                 if (count++ == num) break;
1850                         }
1851                         break;
1852                 }
1853         }
1854
1855         if (!vp) {
1856                 if (return_null) return NULL;
1857                 return vp_aprint_type(ctx, da->type);
1858         }
1859
1860 print:
1861         ret = vp_aprint_value(ctx, vp, '"');
1862
1863 finish:
1864         talloc_free(myvp);
1865         return ret;
1866 }
1867
1868 #ifdef DEBUG_XLAT
1869 static const char xlat_spaces[] = "                                                                                                                                                                                                                                                                ";
1870 #endif
1871
1872 static char *xlat_aprint(TALLOC_CTX *ctx, REQUEST *request, xlat_exp_t const * const node,
1873                          RADIUS_ESCAPE_STRING escape, void *escape_ctx, int lvl)
1874 {
1875         ssize_t rcode;
1876         char *str = NULL, *child;
1877         REQUEST *ref;
1878
1879         XLAT_DEBUG("%.*sxlat aprint %d", lvl, xlat_spaces, node->type);
1880
1881         switch (node->type) {
1882                 /*
1883                  *      Don't escape this.
1884                  */
1885         case XLAT_LITERAL:
1886                 XLAT_DEBUG("xlat_aprint LITERAL");
1887                 return talloc_typed_strdup(ctx, node->fmt);
1888
1889                 /*
1890                  *      Do a one-character expansion.
1891                  */
1892         case XLAT_PERCENT:
1893         {
1894                 char const *p;
1895                 char *nl;
1896                 size_t freespace = 256;
1897                 struct tm ts;
1898                 time_t when;
1899
1900                 XLAT_DEBUG("xlat_aprint PERCENT");
1901
1902                 str = talloc_array(ctx, char, freespace); /* @todo do better allocation */
1903                 p = node->fmt;
1904
1905                 when = request->timestamp;
1906                 if (request->packet) {
1907                         when = request->packet->timestamp.tv_sec;
1908                 }
1909
1910                 switch (*p) {
1911                 case '%':
1912                         str[0] = '%';
1913                         str[1] = '\0';
1914                         break;
1915
1916                 case 'd': /* request day */
1917                         (void) localtime_r(&when, &ts);
1918                         strftime(str, freespace, "%d", &ts);
1919                         break;
1920
1921                 case 'l': /* request timestamp */
1922                         snprintf(str, freespace, "%lu",
1923                                  (unsigned long) when);
1924                         break;
1925
1926                 case 'm': /* request month */
1927                         (void) localtime_r(&when, &ts);
1928                         strftime(str, freespace, "%m", &ts);
1929                         break;
1930
1931                 case 'n': /* Request Number*/
1932                         snprintf(str, freespace, "%u", request->number);
1933                         break;
1934
1935                 case 't': /* request timestamp */
1936                         CTIME_R(&when, str, freespace);
1937                         nl = strchr(str, '\n');
1938                         if (nl) *nl = '\0';
1939                         break;
1940
1941                 case 'D': /* request date */
1942                         (void) localtime_r(&when, &ts);
1943                         strftime(str, freespace, "%Y%m%d", &ts);
1944                         break;
1945
1946                 case 'G': /* request minute */
1947                         (void) localtime_r(&when, &ts);
1948                         strftime(str, freespace, "%M", &ts);
1949                         break;
1950
1951                 case 'H': /* request hour */
1952                         (void) localtime_r(&when, &ts);
1953                         strftime(str, freespace, "%H", &ts);
1954                         break;
1955
1956                 case 'I': /* Request ID */
1957                         if (request->packet) {
1958                                 snprintf(str, freespace, "%i", request->packet->id);
1959                         }
1960                         break;
1961
1962                 case 'S': /* request timestamp in SQL format*/
1963                         (void) localtime_r(&when, &ts);
1964                         strftime(str, freespace, "%Y-%m-%d %H:%M:%S", &ts);
1965                         break;
1966
1967                 case 'T': /* request timestamp */
1968                         (void) localtime_r(&when, &ts);
1969                         strftime(str, freespace, "%Y-%m-%d-%H.%M.%S.000000", &ts);
1970                         break;
1971
1972                 case 'Y': /* request year */
1973                         (void) localtime_r(&when, &ts);
1974                         strftime(str, freespace, "%Y", &ts);
1975                         break;
1976
1977                 case 'v': /* Version of code */
1978                         snprintf(str, freespace, "%s", radiusd_short_version);
1979                         break;
1980
1981                 default:
1982                         rad_assert(0 == 1);
1983                         break;
1984                 }
1985         }
1986                 break;
1987
1988         case XLAT_ATTRIBUTE:
1989                 XLAT_DEBUG("xlat_aprint ATTRIBUTE");
1990                 ref = request;
1991                 if (radius_request(&ref, node->attr.tmpl_request) < 0) {
1992                         return NULL;
1993                 }
1994
1995                 /*
1996                  *      Some attributes are virtual <sigh>
1997                  */
1998                 str = xlat_getvp(ctx, ref, node->attr.tmpl_list, node->attr.tmpl_da, node->attr.tmpl_tag, node->attr.tmpl_num, true);
1999                 if (str) {
2000                         XLAT_DEBUG("EXPAND attr %s", node->attr.tmpl_da->name);
2001                         XLAT_DEBUG("       ---> %s", str);
2002                 }
2003                 break;
2004
2005         case XLAT_VIRTUAL:
2006                 XLAT_DEBUG("xlat_aprint VIRTUAL");
2007                 str = talloc_array(ctx, char, 2048); /* FIXME: have the module call talloc_typed_asprintf */
2008                 rcode = node->xlat->func(node->xlat->instance, request, NULL, str, 2048);
2009                 if (rcode < 0) {
2010                         talloc_free(str);
2011                         return NULL;
2012                 }
2013                 break;
2014
2015         case XLAT_MODULE:
2016                 XLAT_DEBUG("xlat_aprint MODULE");
2017                 if (xlat_process(&child, request, node->child, node->xlat->escape, node->xlat->instance) == 0) {
2018                         return NULL;
2019                 }
2020
2021                 XLAT_DEBUG("%.*sEXPAND mod %s %s", lvl, xlat_spaces, node->fmt, node->child->fmt);
2022                 XLAT_DEBUG("%.*s      ---> %s", lvl, xlat_spaces, child);
2023
2024                 str = talloc_array(ctx, char, 2048); /* FIXME: have the module call talloc_typed_asprintf */
2025                 *str = '\0';    /* Be sure the string is NULL terminated, we now only free on error */
2026
2027                 rcode = node->xlat->func(node->xlat->instance, request, child, str, 2048);
2028                 talloc_free(child);
2029                 if (rcode < 0) {
2030                         talloc_free(str);
2031                         return NULL;
2032                 }
2033                 break;
2034
2035 #ifdef HAVE_REGEX
2036         case XLAT_REGEX:
2037                 XLAT_DEBUG("xlat_aprint REGEX");
2038                 child = request_data_reference(request, request,
2039                                                REQUEST_DATA_REGEX | node->attr.tmpl_num);
2040                 if (!child) return NULL;
2041
2042                 str = talloc_typed_strdup(ctx, child);
2043                 break;
2044 #endif
2045
2046         case XLAT_ALTERNATE:
2047                 XLAT_DEBUG("xlat_aprint ALTERNATE");
2048                 rad_assert(node->child != NULL);
2049                 rad_assert(node->alternate != NULL);
2050
2051                 str = xlat_aprint(ctx, request, node->child, escape, escape_ctx, lvl);
2052                 if (str) break;
2053
2054                 str = xlat_aprint(ctx, request, node->alternate, escape, escape_ctx, lvl);
2055                 break;
2056
2057         }
2058
2059         /*
2060          *      Escape the non-literals we found above.
2061          */
2062         if (str && escape) {
2063                 char *escaped;
2064
2065                 escaped = talloc_array(ctx, char, 2048); /* FIXME: do something intelligent */
2066                 escape(request, escaped, 2038, str, escape_ctx);
2067                 talloc_free(str);
2068                 str = escaped;
2069         }
2070
2071         return str;
2072 }
2073
2074
2075 static size_t xlat_process(char **out, REQUEST *request, xlat_exp_t const * const head,
2076                            RADIUS_ESCAPE_STRING escape, void *escape_ctx)
2077 {
2078         int i, list;
2079         size_t total;
2080         char **array, *answer;
2081         xlat_exp_t const *node;
2082
2083         *out = NULL;
2084
2085         /*
2086          *      There are no nodes to process, so the result is a zero
2087          *      length string.
2088          */
2089         if (!head) {
2090                 *out = talloc_zero_array(request, char, 1);
2091                 return 0;
2092         }
2093
2094         /*
2095          *      Hack for speed.  If it's one expansion, just allocate
2096          *      that and return, instead of allocating an intermediary
2097          *      array.
2098          */
2099         if (!head->next) {
2100                 /*
2101                  *      Pass the MAIN escape function.  Recursive
2102                  *      calls will call node-specific escape
2103                  *      functions.
2104                  */
2105                 answer = xlat_aprint(request, request, head, escape, escape_ctx, 0);
2106                 if (!answer) {
2107                         *out = talloc_zero_array(request, char, 1);
2108                         return 0;
2109                 }
2110                 *out = answer;
2111                 return strlen(answer);
2112         }
2113
2114         list = 0;               /* FIXME: calculate this once */
2115         for (node = head; node != NULL; node = node->next) {
2116                 list++;
2117         }
2118
2119         array = talloc_array(request, char *, list);
2120         if (!array) return -1;
2121
2122         for (node = head, i = 0; node != NULL; node = node->next, i++) {
2123                 array[i] = xlat_aprint(array, request, node, escape, escape_ctx, 0); /* may be NULL */
2124         }
2125
2126         total = 0;
2127         for (i = 0; i < list; i++) {
2128                 if (array[i]) total += strlen(array[i]); /* FIXME: calculate strlen once */
2129         }
2130
2131         if (!total) {
2132                 talloc_free(array);
2133                 *out = talloc_zero_array(request, char, 1);
2134                 return 0;
2135         }
2136
2137         answer = talloc_array(request, char, total + 1);
2138
2139         total = 0;
2140         for (i = 0; i < list; i++) {
2141                 size_t len;
2142
2143                 if (array[i]) {
2144                         len = strlen(array[i]);
2145                         memcpy(answer + total, array[i], len);
2146                         total += len;
2147                 }
2148         }
2149         answer[total] = '\0';
2150         talloc_free(array);     /* and child entries */
2151
2152         *out = answer;
2153         return total;
2154 }
2155
2156
2157 /** Replace %whatever in a string.
2158  *
2159  * See 'doc/variables.txt' for more information.
2160  *
2161  * @param[out] out Where to write pointer to output buffer.
2162  * @param[in] outlen Size of out.
2163  * @param[in] request current request.
2164  * @param[in] node the xlat structure to expand
2165  * @param[in] escape function to escape final value e.g. SQL quoting.
2166  * @param[in] escape_ctx pointer to pass to escape function.
2167  * @return length of string written @bug should really have -1 for failure
2168  */
2169 static ssize_t xlat_expand_struct(char **out, size_t outlen, REQUEST *request, xlat_exp_t const *node,
2170                                   RADIUS_ESCAPE_STRING escape, void *escape_ctx)
2171 {
2172         char *buff;
2173         ssize_t len;
2174
2175         rad_assert(node != NULL);
2176
2177         len = xlat_process(&buff, request, node, escape, escape_ctx);
2178         if ((len < 0) || !buff) {
2179                 rad_assert(buff == NULL);
2180                 if (*out) *out[0] = '\0';
2181                 return len;
2182         }
2183
2184         if (!*out) {
2185                 *out = buff;
2186         } else {
2187                 strlcpy(*out, buff, outlen);
2188                 talloc_free(buff);
2189         }
2190
2191         return strlen(*out);
2192 }
2193
2194 static ssize_t xlat_expand(char **out, size_t outlen, REQUEST *request, char const *fmt,
2195                            RADIUS_ESCAPE_STRING escape, void *escape_ctx) CC_HINT(nonnull (1, 3, 4));
2196
2197 /** Replace %whatever in a string.
2198  *
2199  * See 'doc/variables.txt' for more information.
2200  *
2201  * @param[out] out Where to write pointer to output buffer.
2202  * @param[in] outlen Size of out.
2203  * @param[in] request current request.
2204  * @param[in] fmt string to expand.
2205  * @param[in] escape function to escape final value e.g. SQL quoting.
2206  * @param[in] escape_ctx pointer to pass to escape function.
2207  * @return length of string written @bug should really have -1 for failure
2208  */
2209 static ssize_t CC_HINT(nonnull (1, 3, 4)) xlat_expand(char **out, size_t outlen, REQUEST *request, char const *fmt,
2210                                                       RADIUS_ESCAPE_STRING escape, void *escape_ctx)
2211 {
2212         ssize_t len;
2213         xlat_exp_t *node;
2214
2215         /*
2216          *      Give better errors than the old code.
2217          */
2218         len = xlat_tokenize_request(request, fmt, &node);
2219         if (len == 0) {
2220                 if (*out) {
2221                         *out[0] = '\0';
2222                 } else {
2223                         *out = talloc_zero_array(request, char, 1);
2224                 }
2225                 return 0;
2226         }
2227
2228         if (len < 0) {
2229                 if (*out) *out[0] = '\0';
2230                 return -1;
2231         }
2232
2233         len = xlat_expand_struct(out, outlen, request, node, escape, escape_ctx);
2234         talloc_free(node);
2235
2236         RDEBUG2("EXPAND %s", fmt);
2237         RDEBUG2("   --> %s", *out);
2238
2239         return len;
2240 }
2241
2242 /*
2243  *      Try to convert an xlat to a tmpl for efficiency
2244  */
2245 value_pair_tmpl_t *radius_xlat2tmpl(TALLOC_CTX *ctx, xlat_exp_t *node)
2246 {
2247         value_pair_tmpl_t *vpt;
2248
2249         if (node->next || (node->type != XLAT_ATTRIBUTE)) return NULL;
2250
2251         /*
2252          * @todo it should be possible to emulate the concat and count operations in the
2253          * map code.
2254          */
2255         if ((node->attr.tmpl_num == NUM_COUNT) || (node->attr.tmpl_num == NUM_ALL)) return NULL;
2256
2257         vpt = tmpl_alloc(ctx, TMPL_TYPE_ATTR, node->fmt, -1);
2258         if (!vpt) return NULL;
2259         vpt->tmpl_request = node->attr.tmpl_request;
2260         vpt->tmpl_list = node->attr.tmpl_list;
2261         vpt->tmpl_da = node->attr.tmpl_da;
2262         vpt->tmpl_num = node->attr.tmpl_num;
2263         vpt->tmpl_tag = node->attr.tmpl_tag;
2264
2265         VERIFY_TMPL(vpt);
2266
2267         return vpt;
2268 }
2269
2270 ssize_t radius_xlat(char *out, size_t outlen, REQUEST *request, char const *fmt, RADIUS_ESCAPE_STRING escape, void *ctx)
2271 {
2272         return xlat_expand(&out, outlen, request, fmt, escape, ctx);
2273 }
2274
2275 ssize_t radius_axlat(char **out, REQUEST *request, char const *fmt, RADIUS_ESCAPE_STRING escape, void *ctx)
2276 {
2277         return xlat_expand(out, 0, request, fmt, escape, ctx);
2278 }
2279
2280 ssize_t radius_axlat_struct(char **out, REQUEST *request, xlat_exp_t const *xlat, RADIUS_ESCAPE_STRING escape, void *ctx)
2281 {
2282         return xlat_expand_struct(out, 0, request, xlat, escape, ctx);
2283 }