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 int decode_attribute(const char **from, char **to, int freespace,
660 RADIUS_ESCAPE_STRING func)
663 char *xlat_name, *xlat_string;
664 char *p, *q, *l, *next = NULL;
675 * Copy the input string to an intermediate buffer where
678 varlen = rad_copy_variable(buffer, *from);
680 RDEBUG2("Badly formatted variable: %s", *from);
686 * Kill the %{} around the data we are looking for.
689 p[varlen - 1] = '\0'; /* */
697 * Handle %{%{foo}:-%{bar}}, which is useful, too.
699 * Did I mention that this parser is garbage?
701 if ((p[0] == '%') && (p[1] == '{')) {
706 * 'p' is after the start of 'buffer', so we can
709 len1 = rad_copy_variable(buffer, p);
711 RDEBUG2("Badly formatted variable: %s", p);
716 * They did %{%{foo}}, which is stupid, but allowed.
719 RDEBUG2("Improperly nested variable; %%{%s}", p);
724 * It SHOULD be %{%{foo}:-%{bar}}. If not, it's
727 if ((p[len1] != ':') || (p[len1 + 1] != '-')) {
728 RDEBUG2("No trailing :- after variable at %s", p);
733 * Parse the second bit. The second bit can be
734 * either %{foo}, or a string "foo", or a string
735 * 'foo', or just a bare word: foo
738 l = buffer + len1 + 1;
740 if ((p[0] == '%') && (p[1] == '{')) {
741 len2 = rad_copy_variable(l, p);
744 RDEBUG2("Invalid text after :- at %s", p);
750 } else if ((p[0] == '"') || p[0] == '\'') {
751 getstring(&p, l, strlen(l));
758 * Expand the first one. If we did, exit the
761 retlen = radius_xlat(q, freespace, buffer, request, func);
767 RDEBUG2("\t... expanding second conditional");
769 * Expand / copy the second string if required.
772 retlen = radius_xlat(q, freespace, l,
778 strlcpy(q, l, freespace);
783 * Else the output is an empty string.
789 * See if we're supposed to expand a module name.
792 for (l = p; *l != '\0'; l++) {
799 xlat_name = p; /* start of name */
806 * Module names can't have spaces.
808 if ((*l == ' ') || (*l == '\t')) break;
812 * %{name} is a simple attribute reference,
813 * or regex reference.
816 xlat_name = xlat_string = p;
821 * Maybe it's the old-style %{foo:-bar}
824 RDEBUG2("WARNING: Deprecated conditional expansion \":-\". See \"man unlang\" for details");
827 xlat_string = xlat_name;
833 * FIXME: For backwards "WTF" compatibility, check for
834 * {...}, (after the :), and copy that, too.
837 /* module name, followed by (possibly) per-module string */
841 if ((c = xlat_find(xlat_name)) != NULL) {
842 if (!c->internal) RDEBUG3("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
843 c->module, xlat_string);
844 retlen = c->do_xlat(c->instance, request, xlat_string,
848 snprintf(q, freespace, "%d", retlen);
854 * Expand the second bit.
856 RDEBUG2("\t... expanding second conditional");
857 retlen = radius_xlat(q, freespace, next, request, func);
863 * No attribute by that name, return an error.
865 RDEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
875 * If the caller doesn't pass xlat an escape function, then
876 * we use this one. It simplifies the coding, as the check for
877 * func == NULL only happens once.
879 static size_t xlat_copy(char *out, size_t outlen, const char *in)
881 int freespace = outlen;
883 rad_assert(outlen > 0);
885 while ((*in) && (freespace > 1)) {
889 * FIXME: Do escaping of bad stuff!
897 return (outlen - freespace); /* count does not include NUL */
901 * Replace %<whatever> in a string.
903 * See 'doc/variables.txt' for more information.
905 int radius_xlat(char *out, int outlen, const char *fmt,
906 REQUEST *request, RADIUS_ESCAPE_STRING func)
908 int c, len, freespace;
914 char tmpdt[40]; /* For temporary storing of dates */
920 if (!fmt || !out || !request) return 0;
923 * Ensure that we always have an escaping function.
932 /* Calculate freespace in output */
933 freespace = outlen - (q - out);
938 if ((c != '%') && (c != '$') && (c != '\\')) {
940 * We check if we're inside an open brace. If we are
941 * then we assume this brace is NOT literal, but is
942 * a closing brace and apply it
944 if ((c == '}') && openbraces) {
954 * There's nothing after this character, copy
955 * the last '%' or "$' or '\\' over to the output
981 } else if (c == '%') switch(*p) {
984 if (decode_attribute(&p, &q, freespace, request, func) < 0) return 0;
990 case 'a': /* Protocol: */
991 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL),PW_TYPE_INTEGER, func);
994 case 'c': /* Callback-Number */
995 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER),PW_TYPE_STRING, func);
998 case 'd': /* request day */
999 TM = localtime_r(&request->timestamp, &s_TM);
1000 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
1002 strlcpy(q, tmpdt, freespace);
1007 case 'f': /* Framed IP address */
1008 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS),PW_TYPE_IPADDR, func);
1011 case 'i': /* Calling station ID */
1012 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID),PW_TYPE_STRING, func);
1015 case 'l': /* request timestamp */
1016 snprintf(tmpdt, sizeof(tmpdt), "%lu",
1017 (unsigned long) request->timestamp);
1018 strlcpy(q,tmpdt,freespace);
1022 case 'm': /* request month */
1023 TM = localtime_r(&request->timestamp, &s_TM);
1024 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
1026 strlcpy(q, tmpdt, freespace);
1031 case 'n': /* NAS IP address */
1032 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS),PW_TYPE_IPADDR, func);
1035 case 'p': /* Port number */
1036 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT),PW_TYPE_INTEGER, func);
1039 case 's': /* Speed */
1040 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO),PW_TYPE_STRING, func);
1043 case 't': /* request timestamp */
1044 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
1045 nl = strchr(tmpdt, '\n');
1047 strlcpy(q, tmpdt, freespace);
1051 case 'u': /* User name */
1052 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME),PW_TYPE_STRING, func);
1055 case 'A': /* radacct_dir */
1056 strlcpy(q,radacct_dir,freespace);
1060 case 'C': /* ClientName */
1061 strlcpy(q,request->client->shortname,freespace);
1065 case 'D': /* request date */
1066 TM = localtime_r(&request->timestamp, &s_TM);
1067 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
1069 strlcpy(q, tmpdt, freespace);
1074 case 'H': /* request hour */
1075 TM = localtime_r(&request->timestamp, &s_TM);
1076 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
1078 strlcpy(q, tmpdt, freespace);
1083 case 'L': /* radlog_dir */
1084 strlcpy(q,radlog_dir,freespace);
1089 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU),PW_TYPE_INTEGER, func);
1092 case 'R': /* radius_dir */
1093 strlcpy(q,radius_dir,freespace);
1097 case 'S': /* request timestamp in SQL format*/
1098 TM = localtime_r(&request->timestamp, &s_TM);
1099 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1101 strlcpy(q, tmpdt, freespace);
1106 case 'T': /* request timestamp */
1107 TM = localtime_r(&request->timestamp, &s_TM);
1108 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1110 strlcpy(q, tmpdt, freespace);
1115 case 'U': /* Stripped User name */
1116 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME),PW_TYPE_STRING, func);
1119 case 'V': /* Request-Authenticator */
1120 strlcpy(q,"Verified",freespace);
1124 case 'Y': /* request year */
1125 TM = localtime_r(&request->timestamp, &s_TM);
1126 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1128 strlcpy(q, tmpdt, freespace);
1133 case 'Z': /* Full request pairs except password */
1134 tmp = request->packet->vps;
1135 while (tmp && (freespace > 3)) {
1136 if (tmp->attribute != PW_USER_PASSWORD) {
1138 len = vp_prints(q, freespace - 2, tmp);
1140 freespace -= (len + 2);
1148 RDEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1149 if (freespace > 2) {
1158 RDEBUG2("\texpand: %s -> %s", fmt, out);