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.
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.
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
21 * @brief String expansion ("translation"). Implements %Attribute -> value
23 * @copyright 2000,2006 The FreeRADIUS server project
24 * @copyright 2000 Alan DeKok <aland@ox.org>
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>
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.
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
52 XLAT_REGEX, //!< regex reference
54 XLAT_ALTERNATE //!< xlat conditional syntax :-
58 char const *fmt; //!< The format string.
59 size_t len; //!< Length of the format string.
61 xlat_state_t type; //!< type of this expansion.
62 xlat_exp_t *next; //!< Next in the list.
64 xlat_exp_t *child; //!< Nested expansion.
65 xlat_exp_t *alternate; //!< Alternative expansion if this one expanded to a zero length string.
67 vp_tmpl_t attr; //!< An attribute template.
68 xlat_t const *xlat; //!< The xlat expansion to expand format with.
71 typedef struct xlat_out {
72 char const *out; //!< Output data.
73 size_t len; //!< Length of the output string.
76 static rbtree_t *xlat_root = NULL;
79 static char const * const xlat_foreach_names[] = {"Foreach-Variable-0",
93 static int xlat_inst[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; /* up to 10 for foreach */
95 /** Print length of its RHS.
98 static ssize_t xlat_strlen(UNUSED void *instance, UNUSED REQUEST *request,
99 char const *fmt, char *out, size_t outlen)
101 snprintf(out, outlen, "%u", (unsigned int) strlen(fmt));
105 /** Print the size of the attribute in bytes.
108 static ssize_t xlat_length(UNUSED void *instance, REQUEST *request,
109 char const *fmt, char *out, size_t outlen)
112 while (isspace((int) *fmt)) fmt++;
114 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
119 snprintf(out, outlen, "%zu", vp->vp_length);
123 /** Print data as integer, not as VALUE.
126 static ssize_t xlat_integer(UNUSED void *instance, REQUEST *request,
127 char const *fmt, char *out, size_t outlen)
131 uint64_t int64 = 0; /* Needs to be initialised to zero */
132 uint32_t int32 = 0; /* Needs to be initialised to zero */
134 while (isspace((int) *fmt)) fmt++;
136 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
141 switch (vp->da->type) {
144 if (vp->vp_length > 8) {
148 if (vp->vp_length > 4) {
149 memcpy(&int64, vp->vp_octets, vp->vp_length);
150 return snprintf(out, outlen, "%" PRIu64, htonll(int64));
153 memcpy(&int32, vp->vp_octets, vp->vp_length);
154 return snprintf(out, outlen, "%i", htonl(int32));
156 case PW_TYPE_INTEGER64:
157 return snprintf(out, outlen, "%" PRIu64, vp->vp_integer64);
160 * IP addresses are treated specially, as parsing functions assume the value
161 * is bigendian and will convert it for us.
163 case PW_TYPE_IPV4_ADDR:
164 return snprintf(out, outlen, "%u", htonl(vp->vp_ipaddr));
166 case PW_TYPE_IPV4_PREFIX:
167 return snprintf(out, outlen, "%u", htonl((*(uint32_t *)(vp->vp_ipv4prefix + 2))));
169 case PW_TYPE_INTEGER:
170 return snprintf(out, outlen, "%u", vp->vp_integer);
173 return snprintf(out, outlen, "%u", vp->vp_date);
176 return snprintf(out, outlen, "%u", (unsigned int) vp->vp_byte);
179 return snprintf(out, outlen, "%u", (unsigned int) vp->vp_short);
182 * Ethernet is weird... It's network related, so we assume to it should be
185 case PW_TYPE_ETHERNET:
186 memcpy(&int64, vp->vp_ether, vp->vp_length);
187 return snprintf(out, outlen, "%" PRIu64, htonll(int64));
190 return snprintf(out, outlen, "%i", vp->vp_signed);
192 case PW_TYPE_IPV6_ADDR:
193 return fr_prints_uint128(out, outlen, ntohlll(*(uint128_t const *) &vp->vp_ipv6addr));
195 case PW_TYPE_IPV6_PREFIX:
196 return fr_prints_uint128(out, outlen, ntohlll(*(uint128_t const *) &vp->vp_ipv6prefix[2]));
202 REDEBUG("Type '%s' of length %zu cannot be converted to integer",
203 fr_int2str(dict_attr_types, vp->da->type, "???"), vp->vp_length);
209 /** Print data as hex, not as VALUE.
212 static ssize_t xlat_hex(UNUSED void *instance, REQUEST *request,
213 char const *fmt, char *out, size_t outlen)
221 uint8_t const *buff = NULL;
223 while (isspace((int) *fmt)) fmt++;
225 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
234 if (vp->da->type == PW_TYPE_OCTETS) {
238 * Cast the value_data_t of the VP to an octets string and
242 ret = value_data_cast(request, &dst, PW_TYPE_OCTETS, NULL, vp->da->type,
243 NULL, &vp->data, vp->vp_length);
245 REDEBUG("%s", fr_strerror());
249 p = buff = dst.octets;
255 * Don't truncate the data.
257 if (outlen < (len * 2)) {
258 rad_const_free(buff);
262 for (i = 0; i < len; i++) {
263 snprintf(out + 2*i, 3, "%02x", p[i]);
265 rad_const_free(buff);
270 /** Return the tag of an attribute reference
273 static ssize_t xlat_tag(UNUSED void *instance, REQUEST *request,
274 char const *fmt, char *out, size_t outlen)
278 while (isspace((int) *fmt)) fmt++;
280 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
285 if (!vp->da->flags.has_tag || !TAG_VALID(vp->tag)) {
290 return snprintf(out, outlen, "%u", vp->tag);
293 /** Return the vendor of an attribute reference
296 static ssize_t xlat_vendor(UNUSED void *instance, REQUEST *request,
297 char const *fmt, char *out, size_t outlen)
302 while (isspace((int) *fmt)) fmt++;
304 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
309 vendor = dict_vendorbyvalue(vp->da->vendor);
314 strlcpy(out, vendor->name, outlen);
316 return vendor->length;
319 /** Return the vendor number of an attribute reference
322 static ssize_t xlat_vendor_num(UNUSED void *instance, REQUEST *request,
323 char const *fmt, char *out, size_t outlen)
327 while (isspace((int) *fmt)) fmt++;
329 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
334 return snprintf(out, outlen, "%u", vp->da->vendor);
337 /** Return the attribute name of an attribute reference
340 static ssize_t xlat_attr(UNUSED void *instance, REQUEST *request,
341 char const *fmt, char *out, size_t outlen)
345 while (isspace((int) *fmt)) fmt++;
347 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
351 strlcpy(out, vp->da->name, outlen);
353 return strlen(vp->da->name);
356 /** Return the attribute number of an attribute reference
359 static ssize_t xlat_attr_num(UNUSED void *instance, REQUEST *request,
360 char const *fmt, char *out, size_t outlen)
364 while (isspace((int) *fmt)) fmt++;
366 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
371 return snprintf(out, outlen, "%u", vp->da->attr);
374 /** Print out attribute info
376 * Prints out all instances of a current attribute, or all attributes in a list.
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.
382 * This expands to a zero length string.
384 static ssize_t xlat_debug_attr(UNUSED void *instance, REQUEST *request, char const *fmt,
385 char *out, UNUSED size_t outlen)
392 if (!RDEBUG_ENABLED2) {
397 while (isspace((int) *fmt)) fmt++;
399 if (tmpl_from_attr_str(&vpt, fmt, REQUEST_CURRENT, PAIR_LIST_REQUEST, false, false) <= 0) {
400 RDEBUG("%s", fr_strerror());
404 RIDEBUG("Attributes matching \"%s\"", fmt);
407 for (vp = tmpl_cursor_init(NULL, &cursor, request, &vpt);
409 vp = tmpl_cursor_next(&cursor, &vpt)) {
410 FR_NAME_NUMBER const *type;
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>"),
419 fr_int2str(fr_tokens, vp->op, "<INVALID>"),
422 RIDEBUG2("&%s:%s %s %s",
423 fr_int2str(pair_lists, vpt.tmpl_list, "<INVALID>"),
425 fr_int2str(fr_tokens, vp->op, "<INVALID>"),
430 if (!RDEBUG_ENABLED3) continue;
432 if (vp->da->vendor) {
435 dv = dict_vendorbyvalue(vp->da->vendor);
436 RIDEBUG2("Vendor : %i (%s)", vp->da->vendor, dv ? dv->name : "unknown");
438 RIDEBUG2("Type : %s", fr_int2str(dict_attr_types, vp->da->type, "<INVALID>"));
439 RIDEBUG2("Length : %zu", vp->vp_length);
441 if (!RDEBUG_ENABLED4) continue;
443 type = dict_attr_types;
447 value_data_t *dst = NULL;
451 if ((PW_TYPE) type->number == vp->da->type) {
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 */
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 */
477 value = value_data_aprints(dst, type->number, NULL, dst, (size_t)ret, '\'');
478 if (!value) goto next_type;
480 if ((pad = (11 - strlen(type->name))) < 0) {
485 RDEBUG2("as %s%*s: %s", type->name, pad, " ", value);
498 /** Processes fmt as a map string and applies it to the current request
500 * e.g. "%{map:&User-Name := 'foo'}"
502 * Allows sets of modifications to be cached and then applied.
503 * Useful for processing generic attributes from LDAP.
505 static ssize_t xlat_map(UNUSED void *instance, REQUEST *request,
506 char const *fmt, char *out, size_t outlen)
508 vp_map_t *map = NULL;
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());
519 ret = map_to_request(request, map, map_to_vp, NULL);
522 if (ret < 0) return strlcpy(out, "0", outlen);
524 return strlcpy(out, "1", outlen);
527 /** Prints the current module processing the request
530 static ssize_t xlat_module(UNUSED void *instance, REQUEST *request,
531 UNUSED char const *fmt, char *out, size_t outlen)
533 strlcpy(out, request->module, outlen);
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)
545 if (regex_request_to_sub_named(request, &p, request, fmt) < 0) {
550 len = talloc_array_length(p);
552 RDEBUG("Insufficient buffer space to write subcapture value, needed %zu bytes, have %zu bytes",
556 strlcpy(out, p, outlen);
558 return len - 1; /* - \0 */
563 /** Implements the Foreach-Variable-X
567 static ssize_t xlat_foreach(void *instance, REQUEST *request,
568 UNUSED char const *fmt, char *out, size_t outlen)
574 * See modcall, "FOREACH" for how this works.
576 pvp = (VALUE_PAIR **) request_data_reference(request, (void *)radius_get_vp, *(int*) instance);
582 len = vp_prints_value(out, outlen, *pvp, 0);
583 if (is_truncated(len, outlen)) {
584 RDEBUG("Insufficient buffer space to write foreach value");
592 /** Print data as string, if possible.
594 * If attribute "Foo" is defined as "octets" it will normally
595 * be printed as 0x0a0a0a. The xlat "%{string:Foo}" will instead
598 static ssize_t xlat_string(UNUSED void *instance, REQUEST *request,
599 char const *fmt, char *out, size_t outlen)
606 while (isspace((int) *fmt)) fmt++;
614 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) goto nothing;
616 ret = rad_vp2data(&p, vp);
621 switch (vp->da->type) {
623 len = fr_prints(out, outlen, (char const *) p, vp->vp_length, '"');
627 len = strlcpy(out, vp->vp_strvalue, outlen);
631 len = fr_prints(out, outlen, (char const *) p, ret, '\0');
638 /** xlat expand string attribute value
641 static ssize_t xlat_xlat(UNUSED void *instance, REQUEST *request,
642 char const *fmt, char *out, size_t outlen)
646 while (isspace((int) *fmt)) fmt++;
654 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) goto nothing;
656 return radius_xlat(out, outlen, request, vp->vp_strvalue, NULL, NULL);
659 /** Dynamically change the debugging level for the current request
663 static ssize_t xlat_debug(UNUSED void *instance, REQUEST *request,
664 char const *fmt, char *out, size_t outlen)
669 * Expand to previous (or current) level
671 snprintf(out, outlen, "%d", request->log.lvl);
674 * Assume we just want to get the current value and NOT set it to 0
681 request->log.lvl = RAD_REQUEST_LVL_NONE;
682 request->log.func = NULL;
684 if (level > 4) level = 4;
686 request->log.lvl = level;
687 request->log.func = vradlog_request;
695 * Compare two xlat_t structs, based ONLY on the module name.
697 static int xlat_cmp(void const *one, void const *two)
699 xlat_t const *a = one;
700 xlat_t const *b = two;
702 if (a->length != b->length) {
703 return a->length - b->length;
706 return memcmp(a->name, b->name, a->length);
711 * find the appropriate registered xlat function.
713 static xlat_t *xlat_find(char const *name)
717 strlcpy(my_xlat.name, name, sizeof(my_xlat.name));
718 my_xlat.length = strlen(my_xlat.name);
720 return rbtree_finddata(xlat_root, &my_xlat);
724 /** Register an xlat function.
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
732 int xlat_register(char const *name, xlat_func_t func, xlat_escape_t escape, void *instance)
738 if (!name || !*name) {
739 DEBUG("xlat_register: Invalid xlat name");
744 * First time around, build up the tree...
746 * FIXME: This code should be hoisted out of this function,
747 * and into a global "initialization". But it isn't critical...
754 xlat_root = rbtree_create(NULL, xlat_cmp, NULL, RBTREE_FLAG_REPLACE);
756 DEBUG("xlat_register: Failed to create tree");
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);
770 #define XLAT_REGISTER(_x) xlat_register(STRINGIFY(_x), xlat_ ## _x, NULL, NULL); \
771 c = xlat_find(STRINGIFY(_x)); \
772 rad_assert(c != NULL); \
775 XLAT_REGISTER(integer);
776 XLAT_REGISTER(strlen);
777 XLAT_REGISTER(length);
780 XLAT_REGISTER(vendor);
781 XLAT_REGISTER(vendor_num);
783 XLAT_REGISTER(attr_num);
784 XLAT_REGISTER(string);
787 XLAT_REGISTER(module);
788 XLAT_REGISTER(debug_attr);
789 #if defined(HAVE_REGEX) && defined(HAVE_PCRE)
790 XLAT_REGISTER(regex);
793 xlat_register("debug", xlat_debug, NULL, &xlat_inst[0]);
794 c = xlat_find("debug");
795 rad_assert(c != NULL);
800 * If it already exists, replace the instance.
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);
807 DEBUG("xlat_register: Cannot re-define internal xlat");
813 c->instance = instance;
818 * Doesn't exist. Create it.
820 c = talloc_zero(xlat_root, xlat_t);
824 strlcpy(c->name, name, sizeof(c->name));
825 c->length = strlen(c->name);
826 c->instance = instance;
828 node = rbtree_insert_node(xlat_root, c);
835 * Ensure that the data is deleted when the node is
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.
842 (void) talloc_steal(node, c);
846 /** Unregister an xlat function
848 * We can only have one function to call per name, so the passing of "func"
849 * here is extraneous.
851 * @param[in] name xlat to unregister.
852 * @param[in] func unused.
853 * @param[in] instance data.
855 void xlat_unregister(char const *name, UNUSED xlat_func_t func, void *instance)
860 if (!name || !xlat_root) return;
862 strlcpy(my_xlat.name, name, sizeof(my_xlat.name));
863 my_xlat.length = strlen(my_xlat.name);
865 c = rbtree_finddata(xlat_root, &my_xlat);
868 if (c->instance != instance) return;
870 rbtree_deletebydata(xlat_root, c);
873 static int xlat_unregister_callback(void *instance, void *data)
875 xlat_t *c = (xlat_t *) data;
877 if (c->instance != instance) return 0; /* keep walking */
879 return 2; /* delete it */
882 void xlat_unregister_module(void *instance)
884 rbtree_walk(xlat_root, RBTREE_DELETE_ORDER, xlat_unregister_callback, instance);
888 * Internal redundant handler for xlats
890 typedef enum xlat_redundant_type_t {
894 XLAT_REDUNDANT_LOAD_BALANCE,
895 } xlat_redundant_type_t;
897 typedef struct xlat_redundant_t {
898 xlat_redundant_type_t type;
904 static ssize_t xlat_redundant(void *instance, REQUEST *request,
905 char const *fmt, char *out, size_t outlen)
907 xlat_redundant_t *xr = instance;
912 rad_assert(xr->type == XLAT_REDUNDANT);
915 * Pick the first xlat which succeeds
917 for (ci = cf_item_find_next(xr->cs, NULL);
919 ci = cf_item_find_next(xr->cs, ci)) {
922 if (!cf_item_is_pair(ci)) continue;
924 name = cf_pair_attr(cf_item_to_pair(ci));
925 rad_assert(name != NULL);
927 xlat = xlat_find(name);
930 rcode = xlat->func(xlat->instance, request, fmt, out, outlen);
931 if (rcode <= 0) continue;
936 * Everything failed. Oh well.
943 static ssize_t xlat_load_balance(void *instance, REQUEST *request,
944 char const *fmt, char *out, size_t outlen)
947 xlat_redundant_t *xr = instance;
949 CONF_ITEM *found = NULL;
954 * Choose a child at random.
956 for (ci = cf_item_find_next(xr->cs, NULL);
958 ci = cf_item_find_next(xr->cs, ci)) {
959 if (!cf_item_is_pair(ci)) continue;
963 * Replace the previously found one with a random
966 if ((count * (fr_rand() & 0xffff)) < (uint32_t) 0x10000) {
972 * Plain load balancing: do one child, and only one child.
974 if (xr->type == XLAT_LOAD_BALANCE) {
975 name = cf_pair_attr(cf_item_to_pair(found));
976 rad_assert(name != NULL);
978 xlat = xlat_find(name);
979 if (!xlat) return -1;
981 return xlat->func(xlat->instance, request, fmt, out, outlen);
984 rad_assert(xr->type == XLAT_REDUNDANT_LOAD_BALANCE);
987 * Try the random one we found. If it fails, keep going
988 * through the rest of the children.
992 name = cf_pair_attr(cf_item_to_pair(ci));
993 rad_assert(name != NULL);
995 xlat = xlat_find(name);
999 rcode = xlat->func(xlat->instance, request, fmt, out, outlen);
1000 if (rcode > 0) return rcode;
1004 * Go to the next one, wrapping around at the end.
1006 ci = cf_item_find_next(xr->cs, ci);
1007 if (!ci) ci = cf_item_find_next(xr->cs, NULL);
1008 } while (ci != found);
1014 bool xlat_register_redundant(CONF_SECTION *cs)
1016 char const *name1, *name2;
1017 xlat_redundant_t *xr;
1019 name1 = cf_section_name1(cs);
1020 name2 = cf_section_name2(cs);
1022 if (!name2) return false;
1024 if (xlat_find(name2)) {
1025 cf_log_err_cs(cs, "An expansion is already registered for this name");
1029 xr = talloc_zero(cs, xlat_redundant_t);
1030 if (!xr) return false;
1032 if (strcmp(name1, "redundant") == 0) {
1033 xr->type = XLAT_REDUNDANT;
1035 } else if (strcmp(name1, "redundant-load-balance") == 0) {
1036 xr->type = XLAT_REDUNDANT_LOAD_BALANCE;
1038 } else if (strcmp(name1, "load-balance") == 0) {
1039 xr->type = XLAT_LOAD_BALANCE;
1048 * Get the number of children for load balancing.
1050 if (xr->type == XLAT_REDUNDANT) {
1051 if (xlat_register(name2, xlat_redundant, NULL, xr) < 0) {
1059 for (ci = cf_item_find_next(cs, NULL);
1061 ci = cf_item_find_next(cs, ci)) {
1062 if (!cf_item_is_pair(ci)) continue;
1064 if (!xlat_find(cf_pair_attr(cf_item_to_pair(ci)))) {
1072 if (xlat_register(name2, xlat_load_balance, NULL, xr) < 0) {
1082 /** Crappy temporary function to add attribute ref support to xlats
1084 * This needs to die, and hopefully will die, when xlat functions accept
1085 * xlat node structures.
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.
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.
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.
1098 ssize_t xlat_fmt_to_ref(uint8_t const **out, REQUEST *request, char const *fmt)
1102 while (isspace((int) *fmt)) fmt++;
1104 if (fmt[0] == '&') {
1105 if ((radius_get_vp(&vp, request, fmt) < 0) || !vp) {
1110 return rad_vp2data(out, vp);
1113 *out = (uint8_t const *)fmt;
1117 /** De-register all xlat functions, used mainly for debugging.
1120 void xlat_free(void)
1122 rbtree_free(xlat_root);
1126 # define XLAT_DEBUG DEBUG3
1128 # define XLAT_DEBUG(...)
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);
1138 static ssize_t xlat_tokenize_alternation(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1145 rad_assert(fmt[0] == '%');
1146 rad_assert(fmt[1] == '{');
1147 rad_assert(fmt[2] == '%');
1148 rad_assert(fmt[3] == '{');
1150 XLAT_DEBUG("ALTERNATE <-- %s", fmt);
1152 node = talloc_zero(ctx, xlat_exp_t);
1153 node->type = XLAT_ALTERNATE;
1156 slen = xlat_tokenize_expansion(node, p, &node->child, error);
1159 return slen - (p - fmt);
1165 *error = "Expected ':' after first expansion";
1172 *error = "Expected '-' after ':'";
1178 * Allow the RHS to be empty as a special case.
1182 * Hack up an empty string.
1184 node->alternate = talloc_zero(node, xlat_exp_t);
1185 node->alternate->type = XLAT_LITERAL;
1186 node->alternate->fmt = talloc_typed_strdup(node->alternate, "");
1190 slen = xlat_tokenize_literal(node, p, &node->alternate, true, error);
1193 return slen - (p - fmt);
1196 if (!node->alternate) {
1198 *error = "Empty expansion is invalid";
1208 static ssize_t xlat_tokenize_expansion(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1216 rad_assert(fmt[0] == '%');
1217 rad_assert(fmt[1] == '{');
1222 if ((fmt[2] == '%') && (fmt[3] == '{')) return xlat_tokenize_alternation(ctx, fmt, head, error);
1224 XLAT_DEBUG("EXPANSION <-- %s", fmt);
1225 node = talloc_zero(ctx, xlat_exp_t);
1226 node->fmt = fmt + 2;
1231 * Handle regex's specially.
1234 num = strtol(p, &q, 10);
1235 if (p != q && (*q == '}')) {
1236 XLAT_DEBUG("REGEX <-- %s", fmt);
1239 if ((num > REQUEST_MAX_REGEX) || (num < 0)) {
1241 *error = "Invalid regex reference. Must be in range 0-" STRINGIFY(REQUEST_MAX_REGEX);
1244 node->attr.tmpl_num = num;
1246 node->type = XLAT_REGEX;
1249 return (q - fmt) + 1;
1251 #endif /* HAVE_REGEX */
1256 * %{Tunnel-Password:1}
1257 * %{Tunnel-Password:1[#]}
1258 * %{request:Attr-Name}
1259 * %{request:Tunnel-Password:1}
1260 * %{request:Tunnel-Password:1[#]}
1265 * This is for efficiency, so we don't search for an xlat,
1266 * when what's being referenced is obviously an attribute.
1269 for (q = p; *q != '\0'; q++) {
1270 if (*q == ':') break;
1272 if (isspace((int) *q)) break;
1274 if (*q == '[') continue;
1276 if (*q == '}') break;
1280 * Check for empty expressions %{}
1282 if ((*q == '}') && (q == p)) {
1284 *error = "Empty expression is invalid";
1289 * Might be a module name reference.
1291 * If it's not, it's an attribute or parse error.
1295 node->xlat = xlat_find(node->fmt);
1300 node->type = XLAT_MODULE;
1303 XLAT_DEBUG("MOD <-- %s ... %s", node->fmt, p);
1305 slen = xlat_tokenize_literal(node, p, &node->child, true, error);
1308 return slen - (p - fmt);
1313 rad_assert(node->next == NULL);
1317 *q = ':'; /* Avoids a strdup */
1321 * The first token ends with:
1322 * - '[' - Which is an attribute index, so it must be an attribute.
1323 * - '}' - The end of the expansion, which means it was a bareword.
1325 slen = tmpl_from_attr_substr(&node->attr, p, REQUEST_CURRENT, PAIR_LIST_REQUEST, true, true);
1328 * If the parse error occurred before the ':'
1329 * then the error is changed to 'Unknown module',
1330 * as it was more likely to be a bad module name,
1331 * than a request qualifier.
1333 if ((*q == ':') && ((p + (slen * -1)) < q)) {
1334 *error = "Unknown module";
1336 *error = fr_strerror();
1340 return slen - (p - fmt);
1344 * Might be a virtual XLAT attribute
1346 if (node->attr.type == TMPL_TYPE_ATTR_UNDEFINED) {
1347 node->xlat = xlat_find(node->attr.tmpl_unknown_name);
1348 if (node->xlat && node->xlat->instance && !node->xlat->internal) {
1350 *error = "Missing content in expansion";
1351 return -(p - fmt) - slen;
1355 node->type = XLAT_VIRTUAL;
1356 node->fmt = node->attr.tmpl_unknown_name;
1358 XLAT_DEBUG("VIRTUAL <-- %s", node->fmt);
1360 rad_assert(node->next == NULL);
1366 *error = "Unknown attribute";
1370 node->type = XLAT_ATTRIBUTE;
1375 *error = "No matching closing brace";
1376 return -1; /* second character of format string */
1380 rad_assert(node->next == NULL);
1386 static ssize_t xlat_tokenize_literal(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1387 bool brace, char const **error)
1392 if (!*fmt) return 0;
1394 XLAT_DEBUG("LITERAL <-- %s", fmt);
1396 node = talloc_zero(ctx, xlat_exp_t);
1399 node->type = XLAT_LITERAL;
1407 *error = "Invalid escape at end of string";
1417 * Process the expansion.
1419 if ((p[0] == '%') && (p[1] == '{')) {
1422 XLAT_DEBUG("EXPANSION-2 <-- %s", node->fmt);
1424 slen = xlat_tokenize_expansion(node, p, &node->next, error);
1427 return slen - (p - fmt);
1429 *p = '\0'; /* end the literal */
1432 rad_assert(node->next != NULL);
1435 * Short-circuit the recursive call.
1436 * This saves another function call and
1437 * memory allocation.
1442 * "foo %{User-Name} bar"
1444 * EXPANSION User-Name
1447 slen = xlat_tokenize_literal(node->next, p, &(node->next->next), brace, error);
1448 rad_assert(slen != 0);
1451 return slen - (p - fmt);
1454 brace = false; /* it was found above, or else the above code errored out */
1456 break; /* stop processing the string */
1460 * Check for valid single-character expansions.
1466 if (!p[1] || !strchr("%}dlmntDGHISTYv", p[1])) {
1468 *error = "Invalid variable expansion";
1473 next = talloc_zero(node, xlat_exp_t);
1479 next->fmt = talloc_strndup(next, p + 1, 1);
1481 XLAT_DEBUG("LITERAL-ESCAPED <-- %s", next->fmt);
1482 next->type = XLAT_LITERAL;
1488 XLAT_DEBUG("PERCENT <-- %c", *next->fmt);
1489 next->type = XLAT_PERCENT;
1502 slen = xlat_tokenize_literal(node->next, p, &(node->next->next), brace, error);
1503 rad_assert(slen != 0);
1506 return slen - (p - fmt);
1509 brace = false; /* it was found above, or else the above code errored out */
1511 break; /* stop processing the string */
1515 * If required, eat the brace.
1517 if (brace && (*p == '}')) {
1529 * We were told to look for a brace, but we ran off of
1530 * the end of the string before we found one.
1533 *error = "Missing closing brace at end of string";
1538 * Squash zero-width literals
1540 if (node->len > 0) {
1544 (void) talloc_steal(ctx, node->next);
1553 static char const xlat_tabs[] = " ";
1555 static void xlat_tokenize_debug(xlat_exp_t const *node, int lvl)
1557 rad_assert(node != NULL);
1559 if (lvl >= (int) sizeof(xlat_tabs)) lvl = sizeof(xlat_tabs);
1562 switch (node->type) {
1564 DEBUG("%.*sliteral --> %s", lvl, xlat_tabs, node->fmt);
1568 DEBUG("%.*spercent --> %c", lvl, xlat_tabs, node->fmt[0]);
1571 case XLAT_ATTRIBUTE:
1572 rad_assert(node->attr.tmpl_da != NULL);
1573 DEBUG("%.*sattribute --> %s", lvl, xlat_tabs, node->attr.tmpl_da->name);
1574 rad_assert(node->child == NULL);
1575 if ((node->attr.tmpl_tag != TAG_ANY) || (node->attr.tmpl_num != NUM_ANY)) {
1576 DEBUG("%.*s{", lvl, xlat_tabs);
1578 DEBUG("%.*sref %d", lvl + 1, xlat_tabs, node->attr.tmpl_request);
1579 DEBUG("%.*slist %d", lvl + 1, xlat_tabs, node->attr.tmpl_list);
1581 if (node->attr.tmpl_tag != TAG_ANY) {
1582 DEBUG("%.*stag %d", lvl + 1, xlat_tabs, node->attr.tmpl_tag);
1584 if (node->attr.tmpl_num != NUM_ANY) {
1585 if (node->attr.tmpl_num == NUM_COUNT) {
1586 DEBUG("%.*s[#]", lvl + 1, xlat_tabs);
1587 } else if (node->attr.tmpl_num == NUM_ALL) {
1588 DEBUG("%.*s[*]", lvl + 1, xlat_tabs);
1590 DEBUG("%.*s[%d]", lvl + 1, xlat_tabs, node->attr.tmpl_num);
1594 DEBUG("%.*s}", lvl, xlat_tabs);
1599 rad_assert(node->fmt != NULL);
1600 DEBUG("%.*svirtual --> %s", lvl, xlat_tabs, node->fmt);
1604 rad_assert(node->xlat != NULL);
1605 DEBUG("%.*sxlat --> %s", lvl, xlat_tabs, node->xlat->name);
1607 DEBUG("%.*s{", lvl, xlat_tabs);
1608 xlat_tokenize_debug(node->child, lvl + 1);
1609 DEBUG("%.*s}", lvl, xlat_tabs);
1615 DEBUG("%.*sregex-var --> %d", lvl, xlat_tabs, node->attr.tmpl_num);
1619 case XLAT_ALTERNATE:
1620 DEBUG("%.*sif {", lvl, xlat_tabs);
1621 xlat_tokenize_debug(node->child, lvl + 1);
1622 DEBUG("%.*s}", lvl, xlat_tabs);
1623 DEBUG("%.*selse {", lvl, xlat_tabs);
1624 xlat_tokenize_debug(node->alternate, lvl + 1);
1625 DEBUG("%.*s}", lvl, xlat_tabs);
1632 size_t xlat_sprint(char *buffer, size_t bufsize, xlat_exp_t const *node)
1643 end = buffer + bufsize;
1646 switch (node->type) {
1648 strlcpy(p, node->fmt, end - p);
1654 p[1] = node->fmt[0];
1658 case XLAT_ATTRIBUTE:
1662 if (node->attr.tmpl_request != REQUEST_CURRENT) {
1663 strlcpy(p, fr_int2str(request_refs, node->attr.tmpl_request, "??"), end - p);
1668 if ((node->attr.tmpl_request != REQUEST_CURRENT) ||
1669 (node->attr.tmpl_list != PAIR_LIST_REQUEST)) {
1670 strlcpy(p, fr_int2str(pair_lists, node->attr.tmpl_list, "??"), end - p);
1675 strlcpy(p, node->attr.tmpl_da->name, end - p);
1678 if (node->attr.tmpl_tag != TAG_ANY) {
1680 snprintf(p, end - p, "%u", node->attr.tmpl_tag);
1684 if (node->attr.tmpl_num != NUM_ANY) {
1686 switch (node->attr.tmpl_num) {
1696 snprintf(p, end - p, "%i", node->attr.tmpl_num);
1705 snprintf(p, end - p, "%%{%i}", node->attr.tmpl_num);
1712 strlcpy(p, node->fmt, end - p);
1720 strlcpy(p, node->xlat->name, end - p);
1723 rad_assert(node->child != NULL);
1724 len = xlat_sprint(p, end - p, node->child);
1729 case XLAT_ALTERNATE:
1733 len = xlat_sprint(p, end - p, node->child);
1739 len = xlat_sprint(p, end - p, node->alternate);
1747 if (p == end) break;
1757 ssize_t xlat_tokenize(TALLOC_CTX *ctx, char *fmt, xlat_exp_t **head,
1760 return xlat_tokenize_literal(ctx, fmt, head, false, error);
1764 /** Tokenize an xlat expansion
1766 * @param[in] request the input request. Memory will be attached here.
1767 * @param[in] fmt the format string to expand
1768 * @param[out] head the head of the xlat list / tree structure.
1770 static ssize_t xlat_tokenize_request(REQUEST *request, char const *fmt, xlat_exp_t **head)
1774 char const *error = NULL;
1779 * Copy the original format string to a buffer so that
1780 * the later functions can mangle it in-place, which is
1783 tokens = talloc_typed_strdup(request, fmt);
1784 if (!tokens) return -1;
1786 slen = xlat_tokenize_literal(request, tokens, head, false, &error);
1789 * Zero length expansion, return a zero length node.
1792 *head = talloc_zero(request, xlat_exp_t);
1796 * Output something like:
1799 * " ^ error was here"
1802 talloc_free(tokens);
1803 rad_assert(error != NULL);
1805 REMARKER(fmt, -slen, error);
1809 if (*head && (rad_debug_lvl > 2)) {
1811 DEBUG("Parsed xlat tree:");
1812 xlat_tokenize_debug(*head, 0);
1816 * All of the nodes point to offsets in the "tokens"
1817 * string. Let's ensure that free'ing head will free
1820 (void) talloc_steal(*head, tokens);
1826 static char *xlat_getvp(TALLOC_CTX *ctx, REQUEST *request, vp_tmpl_t const *vpt,
1827 bool escape, bool return_null)
1829 VALUE_PAIR *vp = NULL, *virtual = NULL;
1830 RADIUS_PACKET *packet = NULL;
1835 char quote = escape ? '"' : '\0';
1837 rad_assert((vpt->type == TMPL_TYPE_ATTR) || (vpt->type == TMPL_TYPE_LIST));
1840 * We only support count and concatenate operations on lists.
1842 if (vpt->type == TMPL_TYPE_LIST) {
1843 vp = tmpl_cursor_init(NULL, &cursor, request, vpt);
1848 * See if we're dealing with an attribute in the request
1850 * This allows users to manipulate virtual attributes as if
1851 * they were real ones.
1853 vp = tmpl_cursor_init(NULL, &cursor, request, vpt);
1854 if (vp) goto do_print;
1857 * We didn't find the VP in a list.
1858 * If it's not a virtual one, and we're not meant to
1859 * be counting it, return.
1861 if (!vpt->tmpl_da->flags.virtual) {
1862 if (vpt->tmpl_num == NUM_COUNT) goto do_print;
1867 * Switch out the request to the one specified by the template
1869 if (radius_request(&request, vpt->tmpl_request) < 0) return NULL;
1872 * Some non-packet expansions
1874 switch (vpt->tmpl_da->attr) {
1876 break; /* ignore them */
1878 case PW_CLIENT_SHORTNAME:
1879 if (vpt->tmpl_num == NUM_COUNT) goto count_virtual;
1880 if (request->client && request->client->shortname) {
1881 return talloc_typed_strdup(ctx, request->client->shortname);
1883 return talloc_typed_strdup(ctx, "<UNKNOWN-CLIENT>");
1885 case PW_REQUEST_PROCESSING_STAGE:
1886 if (vpt->tmpl_num == NUM_COUNT) goto count_virtual;
1887 if (request->component) {
1888 return talloc_typed_strdup(ctx, request->component);
1890 return talloc_typed_strdup(ctx, "server_core");
1892 case PW_VIRTUAL_SERVER:
1893 if (vpt->tmpl_num == NUM_COUNT) goto count_virtual;
1894 if (!request->server) return NULL;
1895 return talloc_typed_strdup(ctx, request->server);
1897 case PW_MODULE_RETURN_CODE:
1898 if (vpt->tmpl_num == NUM_COUNT) goto count_virtual;
1899 if (!request->rcode) return NULL;
1900 return talloc_typed_strdup(ctx, fr_int2str(modreturn_table, request->rcode, ""));
1904 * All of the attributes must now refer to a packet.
1905 * If there's no packet, we can't print any attribute
1908 packet = radius_packet(request, vpt->tmpl_list);
1910 if (return_null) return NULL;
1911 return vp_aprints_type(ctx, vpt->tmpl_da->type);
1915 switch (vpt->tmpl_da->attr) {
1919 case PW_PACKET_TYPE:
1920 dv = dict_valbyattr(PW_PACKET_TYPE, 0, packet->code);
1921 if (dv) return talloc_typed_strdup(ctx, dv->name);
1922 return talloc_typed_asprintf(ctx, "%d", packet->code);
1924 case PW_RESPONSE_PACKET_TYPE:
1929 if (request->proxy_reply && (!request->reply || !request->reply->code)) {
1930 code = request->proxy_reply->code;
1933 if (request->reply) {
1934 code = request->reply->code;
1937 return talloc_typed_strdup(ctx, fr_packet_codes[code]);
1941 * Virtual attributes which require a temporary VALUE_PAIR
1942 * to be allocated. We can't use stack allocated memory
1943 * because of the talloc checks sprinkled throughout the
1944 * various VP functions.
1946 case PW_PACKET_AUTHENTICATION_VECTOR:
1947 virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1948 fr_pair_value_memcpy(virtual, packet->vector, sizeof(packet->vector));
1952 case PW_CLIENT_IP_ADDRESS:
1953 case PW_PACKET_SRC_IP_ADDRESS:
1954 if (packet->src_ipaddr.af == AF_INET) {
1955 virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1956 virtual->vp_ipaddr = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
1961 case PW_PACKET_DST_IP_ADDRESS:
1962 if (packet->dst_ipaddr.af == AF_INET) {
1963 virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1964 virtual->vp_ipaddr = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
1969 case PW_PACKET_SRC_IPV6_ADDRESS:
1970 if (packet->src_ipaddr.af == AF_INET6) {
1971 virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1972 memcpy(&virtual->vp_ipv6addr,
1973 &packet->src_ipaddr.ipaddr.ip6addr,
1974 sizeof(packet->src_ipaddr.ipaddr.ip6addr));
1979 case PW_PACKET_DST_IPV6_ADDRESS:
1980 if (packet->dst_ipaddr.af == AF_INET6) {
1981 virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1982 memcpy(&virtual->vp_ipv6addr,
1983 &packet->dst_ipaddr.ipaddr.ip6addr,
1984 sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
1989 case PW_PACKET_SRC_PORT:
1990 virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1991 virtual->vp_integer = packet->src_port;
1995 case PW_PACKET_DST_PORT:
1996 virtual = fr_pair_afrom_da(ctx, vpt->tmpl_da);
1997 virtual->vp_integer = packet->dst_port;
2003 * Fake various operations for virtual attributes.
2006 if (vpt->tmpl_num != NUM_ANY) switch (vpt->tmpl_num) {
2008 * [n] is NULL (we only have [0])
2013 * [*] means only one.
2019 * [#] means 1 (as there's only one)
2023 ret = talloc_strdup(ctx, "1");
2027 * [0] is fine (get the first instance)
2036 switch (vpt->tmpl_num) {
2038 * Return a count of the VPs.
2044 for (vp = tmpl_cursor_init(NULL, &cursor, request, vpt);
2046 vp = tmpl_cursor_next(&cursor, vpt)) count++;
2048 return talloc_typed_asprintf(ctx, "%d", count);
2053 * Concatenate all values together,
2054 * separated by commas.
2060 if (!fr_cursor_current(&cursor)) return NULL;
2061 p = vp_aprints_value(ctx, vp, quote);
2062 if (!p) return NULL;
2064 while ((vp = tmpl_cursor_next(&cursor, vpt)) != NULL) {
2065 q = vp_aprints_value(ctx, vp, quote);
2066 if (!q) return NULL;
2067 p = talloc_strdup_append(p, ",");
2068 p = talloc_strdup_append(p, q);
2076 * The cursor was set to the correct
2077 * position above by tmpl_cursor_init.
2079 vp = fr_cursor_current(&cursor);
2084 if (return_null) return NULL;
2085 return vp_aprints_type(ctx, vpt->tmpl_da->type);
2089 ret = vp_aprints_value(ctx, vp, quote);
2092 talloc_free(virtual);
2097 static const char xlat_spaces[] = " ";
2100 static char *xlat_aprint(TALLOC_CTX *ctx, REQUEST *request, xlat_exp_t const * const node,
2101 xlat_escape_t escape, void *escape_ctx, int lvl)
2104 char *str = NULL, *child;
2107 XLAT_DEBUG("%.*sxlat aprint %d %s", lvl, xlat_spaces, node->type, node->fmt);
2109 switch (node->type) {
2111 * Don't escape this.
2114 XLAT_DEBUG("xlat_aprint LITERAL");
2115 return talloc_typed_strdup(ctx, node->fmt);
2118 * Do a one-character expansion.
2123 size_t freespace = 256;
2127 XLAT_DEBUG("xlat_aprint PERCENT");
2129 str = talloc_array(ctx, char, freespace); /* @todo do better allocation */
2132 when = request->timestamp;
2133 if (request->packet) {
2134 when = request->packet->timestamp.tv_sec;
2143 case 'd': /* request day */
2144 if (!localtime_r(&when, &ts)) goto error;
2145 strftime(str, freespace, "%d", &ts);
2148 case 'l': /* request timestamp */
2149 snprintf(str, freespace, "%lu",
2150 (unsigned long) when);
2153 case 'm': /* request month */
2154 if (!localtime_r(&when, &ts)) goto error;
2155 strftime(str, freespace, "%m", &ts);
2158 case 'n': /* Request Number*/
2159 snprintf(str, freespace, "%u", request->number);
2162 case 't': /* request timestamp */
2163 CTIME_R(&when, str, freespace);
2164 nl = strchr(str, '\n');
2168 case 'D': /* request date */
2169 if (!localtime_r(&when, &ts)) goto error;
2170 strftime(str, freespace, "%Y%m%d", &ts);
2173 case 'G': /* request minute */
2174 if (!localtime_r(&when, &ts)) goto error;
2175 strftime(str, freespace, "%M", &ts);
2178 case 'H': /* request hour */
2179 if (!localtime_r(&when, &ts)) goto error;
2180 strftime(str, freespace, "%H", &ts);
2183 case 'I': /* Request ID */
2184 if (request->packet) {
2185 snprintf(str, freespace, "%i", request->packet->id);
2189 case 'S': /* request timestamp in SQL format*/
2190 if (!localtime_r(&when, &ts)) goto error;
2191 strftime(str, freespace, "%Y-%m-%d %H:%M:%S", &ts);
2194 case 'T': /* request timestamp */
2195 if (!localtime_r(&when, &ts)) goto error;
2196 strftime(str, freespace, "%Y-%m-%d-%H.%M.%S.000000", &ts);
2199 case 'Y': /* request year */
2200 if (!localtime_r(&when, &ts)) {
2202 REDEBUG("Failed converting packet timestamp to localtime: %s", fr_syserror(errno));
2206 strftime(str, freespace, "%Y", &ts);
2209 case 'v': /* Version of code */
2210 RWDEBUG("%%v is deprecated and will be removed. Use ${version.freeradius-server}");
2211 snprintf(str, freespace, "%s", radiusd_version_short);
2221 case XLAT_ATTRIBUTE:
2222 XLAT_DEBUG("xlat_aprint ATTRIBUTE");
2225 * Some attributes are virtual <sigh>
2227 str = xlat_getvp(ctx, request, &node->attr, escape ? false : true, true);
2229 XLAT_DEBUG("EXPAND attr %s", node->attr.tmpl_da->name);
2230 XLAT_DEBUG(" ---> %s", str);
2235 XLAT_DEBUG("xlat_aprint VIRTUAL");
2236 str = talloc_array(ctx, char, 2048); /* FIXME: have the module call talloc_typed_asprintf */
2237 rcode = node->xlat->func(node->xlat->instance, request, NULL, str, 2048);
2242 RDEBUG2("EXPAND %s", node->xlat->name);
2243 RDEBUG2(" --> %s", str);
2247 XLAT_DEBUG("xlat_aprint MODULE");
2250 if (xlat_process(&child, request, node->child, node->xlat->escape, node->xlat->instance) == 0) {
2254 XLAT_DEBUG("%.*sEXPAND mod %s %s", lvl, xlat_spaces, node->fmt, node->child->fmt);
2256 XLAT_DEBUG("%.*sEXPAND mod %s", lvl, xlat_spaces, node->fmt);
2257 child = talloc_typed_strdup(ctx, "");
2260 XLAT_DEBUG("%.*s ---> %s", lvl, xlat_spaces, child);
2265 * The OUTPUT of xlat is a printable string. The INPUT might not be...
2267 * This is really the reverse of fr_prints().
2269 if (cf_new_escape && *child) {
2274 type = PW_TYPE_STRING;
2275 slen = value_data_from_str(request, &data, &type, NULL, child, talloc_array_length(child) - 1, '"');
2289 if (*p == '\\') switch (p[1]) {
2311 str = talloc_array(ctx, char, 2048); /* FIXME: have the module call talloc_typed_asprintf */
2312 *str = '\0'; /* Be sure the string is NULL terminated, we now only free on error */
2314 rcode = node->xlat->func(node->xlat->instance, request, child, str, 2048);
2324 XLAT_DEBUG("xlat_aprint REGEX");
2325 if (regex_request_to_sub(ctx, &str, request, node->attr.tmpl_num) < 0) return NULL;
2330 case XLAT_ALTERNATE:
2331 XLAT_DEBUG("xlat_aprint ALTERNATE");
2332 rad_assert(node->child != NULL);
2333 rad_assert(node->alternate != NULL);
2335 str = xlat_aprint(ctx, request, node->child, escape, escape_ctx, lvl);
2337 XLAT_DEBUG("ALTERNATE got string: %s", str);
2341 XLAT_DEBUG("ALTERNATE going to alternate");
2342 str = xlat_aprint(ctx, request, node->alternate, escape, escape_ctx, lvl);
2348 * If there's no data, return that, instead of an empty string.
2350 if (str && !str[0]) {
2356 * Escape the non-literals we found above.
2358 if (str && escape) {
2361 escaped = talloc_array(ctx, char, 2048); /* FIXME: do something intelligent */
2362 escape(request, escaped, 2038, str, escape_ctx);
2371 static size_t xlat_process(char **out, REQUEST *request, xlat_exp_t const * const head,
2372 xlat_escape_t escape, void *escape_ctx)
2376 char **array, *answer;
2377 xlat_exp_t const *node;
2382 * There are no nodes to process, so the result is a zero
2386 *out = talloc_zero_array(request, char, 1);
2391 * Hack for speed. If it's one expansion, just allocate
2392 * that and return, instead of allocating an intermediary
2397 * Pass the MAIN escape function. Recursive
2398 * calls will call node-specific escape
2401 answer = xlat_aprint(request, request, head, escape, escape_ctx, 0);
2403 *out = talloc_zero_array(request, char, 1);
2407 return strlen(answer);
2410 list = 0; /* FIXME: calculate this once */
2411 for (node = head; node != NULL; node = node->next) {
2415 array = talloc_array(request, char *, list);
2416 if (!array) return -1;
2418 for (node = head, i = 0; node != NULL; node = node->next, i++) {
2419 array[i] = xlat_aprint(array, request, node, escape, escape_ctx, 0); /* may be NULL */
2423 for (i = 0; i < list; i++) {
2424 if (array[i]) total += strlen(array[i]); /* FIXME: calculate strlen once */
2429 *out = talloc_zero_array(request, char, 1);
2433 answer = talloc_array(request, char, total + 1);
2436 for (i = 0; i < list; i++) {
2440 len = strlen(array[i]);
2441 memcpy(answer + total, array[i], len);
2445 answer[total] = '\0';
2446 talloc_free(array); /* and child entries */
2453 /** Replace %whatever in a string.
2455 * See 'doc/configuration/variables.rst' for more information.
2457 * @param[out] out Where to write pointer to output buffer.
2458 * @param[in] outlen Size of out.
2459 * @param[in] request current request.
2460 * @param[in] node the xlat structure to expand
2461 * @param[in] escape function to escape final value e.g. SQL quoting.
2462 * @param[in] escape_ctx pointer to pass to escape function.
2463 * @return length of string written @bug should really have -1 for failure
2465 static ssize_t xlat_expand_struct(char **out, size_t outlen, REQUEST *request, xlat_exp_t const *node,
2466 xlat_escape_t escape, void *escape_ctx)
2471 rad_assert(node != NULL);
2473 len = xlat_process(&buff, request, node, escape, escape_ctx);
2474 if ((len < 0) || !buff) {
2475 rad_assert(buff == NULL);
2476 if (*out) *out[0] = '\0';
2483 * If out doesn't point to an existing buffer
2484 * copy the pointer to our buffer over.
2492 * Otherwise copy the malloced buffer to the fixed one.
2494 strlcpy(*out, buff, outlen);
2499 static ssize_t xlat_expand(char **out, size_t outlen, REQUEST *request, char const *fmt,
2500 xlat_escape_t escape, void *escape_ctx) CC_HINT(nonnull (1, 3, 4));
2502 /** Replace %whatever in a string.
2504 * See 'doc/configuration/variables.rst' for more information.
2506 * @param[out] out Where to write pointer to output buffer.
2507 * @param[in] outlen Size of out.
2508 * @param[in] request current request.
2509 * @param[in] fmt string to expand.
2510 * @param[in] escape function to escape final value e.g. SQL quoting.
2511 * @param[in] escape_ctx pointer to pass to escape function.
2512 * @return length of string written @bug should really have -1 for failure
2514 static ssize_t xlat_expand(char **out, size_t outlen, REQUEST *request, char const *fmt,
2515 xlat_escape_t escape, void *escape_ctx)
2521 * Give better errors than the old code.
2523 len = xlat_tokenize_request(request, fmt, &node);
2528 *out = talloc_zero_array(request, char, 1);
2534 if (*out) *out[0] = '\0';
2538 len = xlat_expand_struct(out, outlen, request, node, escape, escape_ctx);
2541 RDEBUG2("EXPAND %s", fmt);
2542 RDEBUG2(" --> %s", *out);
2547 /** Try to convert an xlat to a tmpl for efficiency
2549 * @param ctx to allocate new vp_tmpl_t in.
2550 * @param node to convert.
2551 * @return NULL if unable to convert (not necessarily error), or a new vp_tmpl_t.
2553 vp_tmpl_t *xlat_to_tmpl_attr(TALLOC_CTX *ctx, xlat_exp_t *node)
2557 if (node->next || (node->type != XLAT_ATTRIBUTE) || (node->attr.type != TMPL_TYPE_ATTR)) return NULL;
2560 * Concat means something completely different as an attribute reference
2561 * Count isn't implemented.
2563 if ((node->attr.tmpl_num == NUM_COUNT) || (node->attr.tmpl_num == NUM_ALL)) return NULL;
2565 vpt = tmpl_alloc(ctx, TMPL_TYPE_ATTR, node->fmt, -1);
2566 if (!vpt) return NULL;
2567 memcpy(&vpt->data, &node->attr.data, sizeof(vpt->data));
2574 /** Try to convert attr tmpl to an xlat for &attr[*] and artificially constructing expansions
2576 * @param ctx to allocate new xlat_expt_t in.
2577 * @param vpt to convert.
2578 * @return NULL if unable to convert (not necessarily error), or a new vp_tmpl_t.
2580 xlat_exp_t *xlat_from_tmpl_attr(TALLOC_CTX *ctx, vp_tmpl_t *vpt)
2584 if (vpt->type != TMPL_TYPE_ATTR) return NULL;
2586 node = talloc_zero(ctx, xlat_exp_t);
2587 node->type = XLAT_ATTRIBUTE;
2588 node->fmt = talloc_bstrndup(node, vpt->name, vpt->len);
2589 tmpl_init(&node->attr, TMPL_TYPE_ATTR, node->fmt, talloc_array_length(node->fmt) - 1);
2590 memcpy(&node->attr.data, &vpt->data, sizeof(vpt->data));
2595 ssize_t radius_xlat(char *out, size_t outlen, REQUEST *request, char const *fmt, xlat_escape_t escape, void *ctx)
2597 return xlat_expand(&out, outlen, request, fmt, escape, ctx);
2600 ssize_t radius_xlat_struct(char *out, size_t outlen, REQUEST *request, xlat_exp_t const *xlat, xlat_escape_t escape, void *ctx)
2602 return xlat_expand_struct(&out, outlen, request, xlat, escape, ctx);
2605 ssize_t radius_axlat(char **out, REQUEST *request, char const *fmt, xlat_escape_t escape, void *ctx)
2607 return xlat_expand(out, 0, request, fmt, escape, ctx);
2610 ssize_t radius_axlat_struct(char **out, REQUEST *request, xlat_exp_t const *xlat, xlat_escape_t escape, void *ctx)
2612 return xlat_expand_struct(out, 0, request, xlat, escape, ctx);