2 * xlat.c Translate strings. This is the first version of xlat
3 * incorporated to RADIUS
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * Copyright 2000,2006 The FreeRADIUS server project
22 * Copyright 2000 Alan DeKok <aland@ox.org>
25 #include <freeradius-devel/ident.h>
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/md5.h>
30 #include <freeradius-devel/rad_assert.h>
34 typedef struct xlat_t {
35 char module[MAX_STRING_LEN];
38 RAD_XLAT_FUNC do_xlat;
39 int internal; /* not allowed to re-define these */
42 static rbtree_t *xlat_root = NULL;
45 * Define all xlat's in the structure.
47 static const char * const internal_xlat[] = {"check",
56 #if REQUEST_MAX_REGEX > 8
57 #error Please fix the following line
59 static const int xlat_inst[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; /* up to 8 for regex */
63 * Convert the value on a VALUE_PAIR to string
65 static int valuepair2str(char * out,int outlen,VALUE_PAIR * pair,
66 int type, RADIUS_ESCAPE_STRING func)
68 char buffer[MAX_STRING_LEN * 4];
71 vp_prints_value(buffer, sizeof(buffer), pair, -1);
72 return func(out, outlen, buffer);
77 strlcpy(out,"_",outlen);
79 case PW_TYPE_INTEGER :
80 strlcpy(out,"0",outlen);
83 strlcpy(out,"?.?.?.?",outlen);
85 case PW_TYPE_IPV6ADDR :
86 strlcpy(out,":?:",outlen);
89 strlcpy(out,"0",outlen);
92 strlcpy(out,"unknown_type",outlen);
99 * Dynamically translate for check:, request:, reply:, etc.
101 static size_t xlat_packet(void *instance, REQUEST *request,
102 char *fmt, char *out, size_t outlen,
103 RADIUS_ESCAPE_STRING func)
107 VALUE_PAIR *vps = NULL;
108 RADIUS_PACKET *packet = NULL;
110 switch (*(int*) instance) {
112 vps = request->config_items;
116 vps = request->packet->vps;
117 packet = request->packet;
121 vps = request->reply->vps;
122 packet = request->reply;
127 if (request->proxy) vps = request->proxy->vps;
128 packet = request->proxy;
134 if (request->proxy_reply) vps = request->proxy_reply->vps;
135 packet = request->proxy_reply;
140 if (request->parent) {
141 vps = request->parent->packet->vps;
142 packet = request->parent->packet;
147 if (request->parent && request->parent->reply) {
148 vps = request->parent->reply->vps;
149 packet = request->parent->reply;
158 * The "format" string is the attribute name.
160 da = dict_attrbyname(fmt);
163 const char *p = strchr(fmt, '[');
167 if (strlen(fmt) > sizeof(buffer)) return 0;
169 strlcpy(buffer, fmt, p - fmt + 1);
171 da = dict_attrbyname(buffer);
175 * %{Attribute-Name[#]} returns the count of
176 * attributes of that name in the list.
178 if ((p[1] == '#') && (p[2] == ']')) {
181 for (vp = pairfind(vps, da->attr);
183 vp = pairfind(vp->next, da->attr)) {
186 snprintf(out, outlen, "%d", (int) count);
191 * %{Attribute-Name[*]} returns ALL of the
192 * the attributes, separated by a newline.
194 if ((p[1] == '*') && (p[2] == ']')) {
197 for (vp = pairfind(vps, da->attr);
199 vp = pairfind(vp->next, da->attr)) {
200 count = valuepair2str(out, outlen - 1, vp, da->type, func);
201 rad_assert(count <= outlen);
203 outlen -= (count + 1);
208 if (outlen == 0) break;
219 p += 1 + strspn(p + 1, "0123456789");
221 RDEBUG2("xlat: Invalid array reference in string at %s %s",
227 * Find the N'th value.
229 for (vp = pairfind(vps, da->attr);
231 vp = pairfind(vp->next, da->attr)) {
232 if (count == 0) break;
237 * Non-existent array reference.
241 return valuepair2str(out, outlen, vp, da->type, func);
244 vp = pairfind(vps, da->attr);
247 * Some "magic" handlers, which are never in VP's, but
248 * which are in the packet.
250 * FIXME: We should really do this in a more
256 memset(&localvp, 0, sizeof(localvp));
263 dval = dict_valbyattr(da->attr, packet->code);
265 snprintf(out, outlen, "%s", dval->name);
267 snprintf(out, outlen, "%d", packet->code);
273 case PW_CLIENT_SHORTNAME:
274 if (request->client && request->client->shortname) {
275 strlcpy(out, request->client->shortname, outlen);
277 strlcpy(out, "<UNKNOWN-CLIENT>", outlen);
281 case PW_CLIENT_IP_ADDRESS: /* the same as below */
282 case PW_PACKET_SRC_IP_ADDRESS:
283 if (packet->src_ipaddr.af != AF_INET) {
286 localvp.attribute = da->attr;
287 localvp.vp_ipaddr = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
290 case PW_PACKET_DST_IP_ADDRESS:
291 if (packet->dst_ipaddr.af != AF_INET) {
294 localvp.attribute = da->attr;
295 localvp.vp_ipaddr = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
298 case PW_PACKET_SRC_PORT:
299 localvp.attribute = da->attr;
300 localvp.vp_integer = packet->src_port;
303 case PW_PACKET_DST_PORT:
304 localvp.attribute = da->attr;
305 localvp.vp_integer = packet->dst_port;
308 case PW_PACKET_AUTHENTICATION_VECTOR:
309 localvp.attribute = da->attr;
310 memcpy(localvp.vp_strvalue, packet->vector,
311 sizeof(packet->vector));
312 localvp.length = sizeof(packet->vector);
316 * Authorization, accounting, etc.
318 case PW_REQUEST_PROCESSING_STAGE:
319 if (request->component) {
320 strlcpy(out, request->component, outlen);
322 strlcpy(out, "server_core", outlen);
326 case PW_PACKET_SRC_IPV6_ADDRESS:
327 if (packet->src_ipaddr.af != AF_INET6) {
330 localvp.attribute = da->attr;
331 memcpy(localvp.vp_strvalue,
332 &packet->src_ipaddr.ipaddr.ip6addr,
333 sizeof(packet->src_ipaddr.ipaddr.ip6addr));
336 case PW_PACKET_DST_IPV6_ADDRESS:
337 if (packet->dst_ipaddr.af != AF_INET6) {
340 localvp.attribute = da->attr;
341 memcpy(localvp.vp_strvalue,
342 &packet->dst_ipaddr.ipaddr.ip6addr,
343 sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
346 case PW_VIRTUAL_SERVER:
347 if (!request->server) return 0;
349 snprintf(out, outlen, "%s", request->server);
353 case PW_MODULE_RETURN_CODE:
354 localvp.attribute = da->attr;
357 * See modcall.c for a bit of a hack.
359 localvp.vp_integer = request->simul_max;
363 return 0; /* not found */
367 localvp.type = da->type;
368 return valuepair2str(out, outlen, &localvp,
378 if (!vps) return 0; /* silently fail */
381 * Convert the VP to a string, and return it.
383 return valuepair2str(out, outlen, vp, da->type, func);
388 * Pull %{0} to %{8} out of the packet.
390 static size_t xlat_regex(void *instance, REQUEST *request,
391 char *fmt, char *out, size_t outlen,
392 RADIUS_ESCAPE_STRING func)
397 * We cheat: fmt is "0" to "8", but those numbers
398 * are already in the "instance".
400 fmt = fmt; /* -Wunused */
401 func = func; /* -Wunused FIXME: do escaping? */
403 regex = request_data_reference(request, request,
404 REQUEST_DATA_REGEX | *(int *)instance);
405 if (!regex) return 0;
408 * Copy UP TO "freespace" bytes, including
411 strlcpy(out, regex, outlen);
414 #endif /* HAVE_REGEX_H */
418 * Change the debugging level.
420 static size_t xlat_debug(UNUSED void *instance, REQUEST *request,
421 char *fmt, char *out, size_t outlen,
422 UNUSED RADIUS_ESCAPE_STRING func)
426 if (*fmt) level = atoi(fmt);
429 request->options = RAD_REQUEST_OPTION_NONE;
430 request->radlog = NULL;
432 if (level > 4) level = 4;
434 request->options = level;
435 request->radlog = radlog_request;
438 snprintf(out, outlen, "%d", level);
444 * Calculate the MD5 hash of a string.
446 static size_t xlat_md5(UNUSED void *instance, REQUEST *request,
447 char *fmt, char *out, size_t outlen,
448 UNUSED RADIUS_ESCAPE_STRING func)
455 if (!radius_xlat(buffer, sizeof(buffer), fmt, request, func)) {
461 fr_MD5Update(&ctx, (void *) buffer, strlen(buffer));
462 fr_MD5Final(digest, &ctx);
465 snprintf(out, outlen, "md5_overflow");
469 for (i = 0; i < 16; i++) {
470 snprintf(out + i * 2, 3, "%02x", digest[i]);
477 * Compare two xlat_t structs, based ONLY on the module name.
479 static int xlat_cmp(const void *a, const void *b)
481 if (((const xlat_t *)a)->length != ((const xlat_t *)b)->length) {
482 return ((const xlat_t *)a)->length - ((const xlat_t *)b)->length;
485 return memcmp(((const xlat_t *)a)->module,
486 ((const xlat_t *)b)->module,
487 ((const xlat_t *)a)->length);
492 * find the appropriate registered xlat function.
494 static xlat_t *xlat_find(const char *module)
499 * Look for dictionary attributes first.
501 if ((dict_attrbyname(module) != NULL) ||
502 (strchr(module, '[') != NULL)) {
506 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
507 my_xlat.length = strlen(my_xlat.module);
509 return rbtree_finddata(xlat_root, &my_xlat);
514 * Register an xlat function.
516 int xlat_register(const char *module, RAD_XLAT_FUNC func, void *instance)
521 if ((module == NULL) || (strlen(module) == 0)) {
522 DEBUG("xlat_register: Invalid module name");
527 * First time around, build up the tree...
529 * FIXME: This code should be hoisted out of this function,
530 * and into a global "initialization". But it isn't critical...
538 xlat_root = rbtree_create(xlat_cmp, free, 0);
540 DEBUG("xlat_register: Failed to create tree.");
545 * Register the internal packet xlat's.
547 for (i = 0; internal_xlat[i] != NULL; i++) {
548 xlat_register(internal_xlat[i], xlat_packet, &xlat_inst[i]);
549 c = xlat_find(internal_xlat[i]);
550 rad_assert(c != NULL);
555 * New name: "control"
557 xlat_register("control", xlat_packet, &xlat_inst[0]);
558 c = xlat_find("control");
559 rad_assert(c != NULL);
564 * Register xlat's for regexes.
567 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
569 xlat_register(buffer, xlat_regex, &xlat_inst[i]);
570 c = xlat_find(buffer);
571 rad_assert(c != NULL);
574 #endif /* HAVE_REGEX_H */
577 xlat_register("debug", xlat_debug, &xlat_inst[0]);
578 c = xlat_find("debug");
579 rad_assert(c != NULL);
582 xlat_register("md5", xlat_md5, &xlat_inst[0]);
583 c = xlat_find("md5");
584 rad_assert(c != NULL);
589 * If it already exists, replace the instance.
591 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
592 my_xlat.length = strlen(my_xlat.module);
593 c = rbtree_finddata(xlat_root, &my_xlat);
596 DEBUG("xlat_register: Cannot re-define internal xlat");
601 c->instance = instance;
606 * Doesn't exist. Create it.
608 c = rad_malloc(sizeof(*c));
609 memset(c, 0, sizeof(*c));
612 strlcpy(c->module, module, sizeof(c->module));
613 c->length = strlen(c->module);
614 c->instance = instance;
616 rbtree_insert(xlat_root, c);
622 * Unregister an xlat function.
624 * We can only have one function to call per name, so the
625 * passing of "func" here is extraneous.
627 void xlat_unregister(const char *module, RAD_XLAT_FUNC func)
632 func = func; /* -Wunused */
636 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
637 my_xlat.length = strlen(my_xlat.module);
639 node = rbtree_find(xlat_root, &my_xlat);
642 rbtree_delete(xlat_root, node);
646 * De-register all xlat functions,
647 * used mainly for debugging.
651 rbtree_free(xlat_root);
656 * Decode an attribute name into a string.
658 static void decode_attribute(const char **from, char **to, int freespace,
659 int *open_p, REQUEST *request,
660 RADIUS_ESCAPE_STRING func)
664 char *xlat_string = NULL; /* can be large */
665 int free_xlat_string = FALSE;
668 int found=0, retlen=0;
669 int openbraces = *open_p;
680 * Skip the '{' at the front of 'p'
681 * Increment open braces
692 * Handle %{%{foo}:-%{bar}}, which is useful, too.
694 * Did I mention that this parser is garbage?
696 if ((p[0] == '%') && (p[1] == '{')) {
698 * This is really bad, but it works.
701 size_t mylen = strlen(p);
702 char *first = rad_malloc(mylen + 1);
703 char *second = rad_malloc(mylen + 1);
706 len1 = rad_copy_variable(first, p);
708 RDEBUG2("Badly formatted variable: %s", p);
712 if ((p[len1] != ':') || (p[len1 + 1] != '-')) {
713 RDEBUG2("No trailing :- after variable at %s", p);
719 if ((p[0] == '%') && (p[1] == '{')) {
720 len2 = rad_copy_variable(second, p);
724 RDEBUG2("Invalid text after :- at %s", p);
729 } else if ((p[0] == '"') || p[0] == '\'') {
730 getstring(&p, second, mylen);
735 while (*p && (*p != '}')) {
742 RDEBUG2("Failed to find trailing '}' in string");
746 mylen = radius_xlat(q, freespace, first, request, func);
753 strlcpy(q, second, freespace);
756 mylen = radius_xlat(q, freespace, second,
765 * Else the output is an empty string.
775 * First, copy the xlat key name to one buffer
777 while (*p && (*p != '}') && (*p != ':')) {
780 if (pa >= (xlat_name + sizeof(xlat_name) - 1)) {
782 * Skip to the end of the input
785 RDEBUG("xlat: Module name is too long in string %%%s",
793 RDEBUG("xlat: Invalid syntax in %s", *from);
796 * %{name} is a simple attribute reference,
797 * or regex reference.
799 } else if (*p == '}') {
801 rad_assert(openbraces == *open_p);
804 xlat_string = xlat_name;
807 } else if ((p[0] == ':') && (p[1] == '-')) { /* handle ':- */
808 RDEBUG2("WARNING: Deprecated conditional expansion \":-\". See \"man unlang\" for details");
810 xlat_string = xlat_name;
813 } else { /* module name, followed by per-module string */
815 int delimitbrace = *open_p;
817 rad_assert(*p == ':');
818 p++; /* skip the ':' */
821 * If there's a brace immediately following the colon,
822 * then we've chosen to delimite the per-module string,
823 * so keep track of that.
826 delimitbrace = openbraces;
831 xlat_string = rad_malloc(strlen(p) + 1); /* always returns */
832 free_xlat_string = TRUE;
836 * Copy over the rest of the string, which is per-module
839 while (*p && !stop) {
843 * What the heck is this supposed
852 if (!spaces && p[1] == '-') {
861 * This is pretty hokey... we
862 * should use the functions in
872 if (openbraces == delimitbrace) {
894 * Now check to see if we're at the end of the string
895 * we were sent. If we're not, check for :-
897 if (openbraces == delimitbrace) {
898 if (p[0] == ':' && p[1] == '-') {
904 * Look up almost everything in the new tree of xlat
905 * functions. This makes it a little quicker...
908 if ((c = xlat_find(xlat_name)) != NULL) {
909 if (!c->internal) RDEBUG3("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
910 c->module, xlat_string);
911 retlen = c->do_xlat(c->instance, request, xlat_string,
913 /* If retlen is 0, treat it as not found */
914 if (retlen > 0) found = 1;
919 * No attribute by that name, return an error.
921 RDEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
927 * Skip to last '}' if attr is found
928 * The rest of the stuff within the braces is
929 * useless if we found what we need
933 snprintf(q, freespace, "%d", retlen);
939 while((*p != '\0') && (openbraces > *open_p)) {
941 * Handle escapes outside of the loop.
946 p++; /* get & ignore next character */
965 p++; /* skip the character */
970 if (free_xlat_string) free(xlat_string);
972 *open_p = openbraces;
978 * If the caller doesn't pass xlat an escape function, then
979 * we use this one. It simplifies the coding, as the check for
980 * func == NULL only happens once.
982 static size_t xlat_copy(char *out, size_t outlen, const char *in)
984 int freespace = outlen;
986 rad_assert(outlen > 0);
988 while ((*in) && (freespace > 1)) {
992 * FIXME: Do escaping of bad stuff!
1000 return (outlen - freespace); /* count does not include NUL */
1004 * Replace %<whatever> in a string.
1006 * See 'doc/variables.txt' for more information.
1008 int radius_xlat(char *out, int outlen, const char *fmt,
1009 REQUEST *request, RADIUS_ESCAPE_STRING func)
1011 int c, len, freespace;
1016 struct tm *TM, s_TM;
1017 char tmpdt[40]; /* For temporary storing of dates */
1021 * Catch bad modules.
1023 if (!fmt || !out || !request) return 0;
1026 * Ensure that we always have an escaping function.
1035 /* Calculate freespace in output */
1036 freespace = outlen - (q - out);
1041 if ((c != '%') && (c != '$') && (c != '\\')) {
1043 * We check if we're inside an open brace. If we are
1044 * then we assume this brace is NOT literal, but is
1045 * a closing brace and apply it
1047 if ((c == '}') && openbraces) {
1057 * There's nothing after this character, copy
1058 * the last '%' or "$' or '\\' over to the output
1084 } else if (c == '%') switch(*p) {
1086 decode_attribute(&p, &q, freespace, &openbraces, request, func);
1092 case 'a': /* Protocol: */
1093 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL),PW_TYPE_INTEGER, func);
1096 case 'c': /* Callback-Number */
1097 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER),PW_TYPE_STRING, func);
1100 case 'd': /* request day */
1101 TM = localtime_r(&request->timestamp, &s_TM);
1102 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
1104 strlcpy(q, tmpdt, freespace);
1109 case 'f': /* Framed IP address */
1110 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS),PW_TYPE_IPADDR, func);
1113 case 'i': /* Calling station ID */
1114 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID),PW_TYPE_STRING, func);
1117 case 'l': /* request timestamp */
1118 snprintf(tmpdt, sizeof(tmpdt), "%lu",
1119 (unsigned long) request->received.tv_sec);
1120 strlcpy(q,tmpdt,freespace);
1124 case 'm': /* request month */
1125 TM = localtime_r(&request->timestamp, &s_TM);
1126 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
1128 strlcpy(q, tmpdt, freespace);
1133 case 'n': /* NAS IP address */
1134 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS),PW_TYPE_IPADDR, func);
1137 case 'p': /* Port number */
1138 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT),PW_TYPE_INTEGER, func);
1141 case 's': /* Speed */
1142 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO),PW_TYPE_STRING, func);
1145 case 't': /* request timestamp */
1146 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
1147 nl = strchr(tmpdt, '\n');
1149 strlcpy(q, tmpdt, freespace);
1153 case 'u': /* User name */
1154 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME),PW_TYPE_STRING, func);
1157 case 'A': /* radacct_dir */
1158 strlcpy(q,radacct_dir,freespace);
1162 case 'C': /* ClientName */
1163 strlcpy(q,request->client->shortname,freespace);
1167 case 'D': /* request date */
1168 TM = localtime_r(&request->timestamp, &s_TM);
1169 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
1171 strlcpy(q, tmpdt, freespace);
1176 case 'H': /* request hour */
1177 TM = localtime_r(&request->timestamp, &s_TM);
1178 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
1180 strlcpy(q, tmpdt, freespace);
1185 case 'L': /* radlog_dir */
1186 strlcpy(q,radlog_dir,freespace);
1191 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU),PW_TYPE_INTEGER, func);
1194 case 'R': /* radius_dir */
1195 strlcpy(q,radius_dir,freespace);
1199 case 'S': /* request timestamp in SQL format*/
1200 TM = localtime_r(&request->timestamp, &s_TM);
1201 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1203 strlcpy(q, tmpdt, freespace);
1208 case 'T': /* request timestamp */
1209 TM = localtime_r(&request->timestamp, &s_TM);
1210 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1212 strlcpy(q, tmpdt, freespace);
1217 case 'U': /* Stripped User name */
1218 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME),PW_TYPE_STRING, func);
1221 case 'V': /* Request-Authenticator */
1222 strlcpy(q,"Verified",freespace);
1226 case 'Y': /* request year */
1227 TM = localtime_r(&request->timestamp, &s_TM);
1228 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1230 strlcpy(q, tmpdt, freespace);
1235 case 'Z': /* Full request pairs except password */
1236 tmp = request->packet->vps;
1237 while (tmp && (freespace > 3)) {
1238 if (tmp->attribute != PW_USER_PASSWORD) {
1240 len = vp_prints(q, freespace - 2, tmp);
1242 freespace -= (len + 2);
1250 RDEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1251 if (freespace > 2) {
1260 RDEBUG2("\texpand: %s -> %s", fmt, out);