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);
162 int do_number = FALSE;
167 if (strlen(fmt) > sizeof(buffer)) return 0;
169 DEBUG("GOT SHIT %s", fmt);
171 p = strchr(fmt, '[');
173 p = strchr(fmt, '#');
178 strlcpy(buffer, fmt, p - fmt + 1);
180 da = dict_attrbyname(buffer);
184 vp = pairfind(vps, da->attr);
191 case PW_TYPE_INTEGER:
195 snprintf(out, outlen, "%u", vp->lvalue);
203 * %{Attribute-Name[#]} returns the count of
204 * attributes of that name in the list.
206 if ((p[1] == '#') && (p[2] == ']')) {
209 for (vp = pairfind(vps, da->attr);
211 vp = pairfind(vp->next, da->attr)) {
214 snprintf(out, outlen, "%d", (int) count);
219 * %{Attribute-Name[*]} returns ALL of the
220 * the attributes, separated by a newline.
222 if ((p[1] == '*') && (p[2] == ']')) {
225 for (vp = pairfind(vps, da->attr);
227 vp = pairfind(vp->next, da->attr)) {
228 count = valuepair2str(out, outlen - 1, vp, da->type, func);
229 rad_assert(count <= outlen);
231 outlen -= (count + 1);
236 if (outlen == 0) break;
247 p += 1 + strspn(p + 1, "0123456789");
249 RDEBUG2("xlat: Invalid array reference in string at %s %s",
255 * Find the N'th value.
257 for (vp = pairfind(vps, da->attr);
259 vp = pairfind(vp->next, da->attr)) {
260 if (count == 0) break;
265 * Non-existent array reference.
269 return valuepair2str(out, outlen, vp, da->type, func);
272 vp = pairfind(vps, da->attr);
275 * Some "magic" handlers, which are never in VP's, but
276 * which are in the packet.
278 * FIXME: We should really do this in a more
284 memset(&localvp, 0, sizeof(localvp));
291 dval = dict_valbyattr(da->attr, packet->code);
293 snprintf(out, outlen, "%s", dval->name);
295 snprintf(out, outlen, "%d", packet->code);
301 case PW_CLIENT_SHORTNAME:
302 if (request->client && request->client->shortname) {
303 strlcpy(out, request->client->shortname, outlen);
305 strlcpy(out, "<UNKNOWN-CLIENT>", outlen);
309 case PW_CLIENT_IP_ADDRESS: /* the same as below */
310 case PW_PACKET_SRC_IP_ADDRESS:
311 if (packet->src_ipaddr.af != AF_INET) {
314 localvp.attribute = da->attr;
315 localvp.vp_ipaddr = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
318 case PW_PACKET_DST_IP_ADDRESS:
319 if (packet->dst_ipaddr.af != AF_INET) {
322 localvp.attribute = da->attr;
323 localvp.vp_ipaddr = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
326 case PW_PACKET_SRC_PORT:
327 localvp.attribute = da->attr;
328 localvp.vp_integer = packet->src_port;
331 case PW_PACKET_DST_PORT:
332 localvp.attribute = da->attr;
333 localvp.vp_integer = packet->dst_port;
336 case PW_PACKET_AUTHENTICATION_VECTOR:
337 localvp.attribute = da->attr;
338 memcpy(localvp.vp_strvalue, packet->vector,
339 sizeof(packet->vector));
340 localvp.length = sizeof(packet->vector);
344 * Authorization, accounting, etc.
346 case PW_REQUEST_PROCESSING_STAGE:
347 if (request->component) {
348 strlcpy(out, request->component, outlen);
350 strlcpy(out, "server_core", outlen);
354 case PW_PACKET_SRC_IPV6_ADDRESS:
355 if (packet->src_ipaddr.af != AF_INET6) {
358 localvp.attribute = da->attr;
359 memcpy(localvp.vp_strvalue,
360 &packet->src_ipaddr.ipaddr.ip6addr,
361 sizeof(packet->src_ipaddr.ipaddr.ip6addr));
364 case PW_PACKET_DST_IPV6_ADDRESS:
365 if (packet->dst_ipaddr.af != AF_INET6) {
368 localvp.attribute = da->attr;
369 memcpy(localvp.vp_strvalue,
370 &packet->dst_ipaddr.ipaddr.ip6addr,
371 sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
374 case PW_VIRTUAL_SERVER:
375 if (!request->server) return 0;
377 snprintf(out, outlen, "%s", request->server);
381 case PW_MODULE_RETURN_CODE:
382 localvp.attribute = da->attr;
385 * See modcall.c for a bit of a hack.
387 localvp.vp_integer = request->simul_max;
391 return 0; /* not found */
395 localvp.type = da->type;
396 return valuepair2str(out, outlen, &localvp,
406 if (!vps) return 0; /* silently fail */
409 * Convert the VP to a string, and return it.
411 return valuepair2str(out, outlen, vp, da->type, func);
416 * Pull %{0} to %{8} out of the packet.
418 static size_t xlat_regex(void *instance, REQUEST *request,
419 char *fmt, char *out, size_t outlen,
420 RADIUS_ESCAPE_STRING func)
425 * We cheat: fmt is "0" to "8", but those numbers
426 * are already in the "instance".
428 fmt = fmt; /* -Wunused */
429 func = func; /* -Wunused FIXME: do escaping? */
431 regex = request_data_reference(request, request,
432 REQUEST_DATA_REGEX | *(int *)instance);
433 if (!regex) return 0;
436 * Copy UP TO "freespace" bytes, including
439 strlcpy(out, regex, outlen);
442 #endif /* HAVE_REGEX_H */
446 * Change the debugging level.
448 static size_t xlat_debug(UNUSED void *instance, REQUEST *request,
449 char *fmt, char *out, size_t outlen,
450 UNUSED RADIUS_ESCAPE_STRING func)
454 if (*fmt) level = atoi(fmt);
457 request->options = RAD_REQUEST_OPTION_NONE;
458 request->radlog = NULL;
460 if (level > 4) level = 4;
462 request->options = level;
463 request->radlog = radlog_request;
466 snprintf(out, outlen, "%d", level);
472 * Calculate the MD5 hash of a string.
474 static size_t xlat_md5(UNUSED void *instance, REQUEST *request,
475 char *fmt, char *out, size_t outlen,
476 UNUSED RADIUS_ESCAPE_STRING func)
483 if (!radius_xlat(buffer, sizeof(buffer), fmt, request, func)) {
489 fr_MD5Update(&ctx, (void *) buffer, strlen(buffer));
490 fr_MD5Final(digest, &ctx);
493 snprintf(out, outlen, "md5_overflow");
497 for (i = 0; i < 16; i++) {
498 snprintf(out + i * 2, 3, "%02x", digest[i]);
505 * Compare two xlat_t structs, based ONLY on the module name.
507 static int xlat_cmp(const void *a, const void *b)
509 if (((const xlat_t *)a)->length != ((const xlat_t *)b)->length) {
510 return ((const xlat_t *)a)->length - ((const xlat_t *)b)->length;
513 return memcmp(((const xlat_t *)a)->module,
514 ((const xlat_t *)b)->module,
515 ((const xlat_t *)a)->length);
520 * find the appropriate registered xlat function.
522 static xlat_t *xlat_find(const char *module)
527 * Look for dictionary attributes first.
529 if ((dict_attrbyname(module) != NULL) ||
530 (strchr(module, '[') != NULL) ||
531 (strchr(module, '#') != NULL)) {
535 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
536 my_xlat.length = strlen(my_xlat.module);
538 return rbtree_finddata(xlat_root, &my_xlat);
543 * Register an xlat function.
545 int xlat_register(const char *module, RAD_XLAT_FUNC func, void *instance)
550 if ((module == NULL) || (strlen(module) == 0)) {
551 DEBUG("xlat_register: Invalid module name");
556 * First time around, build up the tree...
558 * FIXME: This code should be hoisted out of this function,
559 * and into a global "initialization". But it isn't critical...
567 xlat_root = rbtree_create(xlat_cmp, free, 0);
569 DEBUG("xlat_register: Failed to create tree.");
574 * Register the internal packet xlat's.
576 for (i = 0; internal_xlat[i] != NULL; i++) {
577 xlat_register(internal_xlat[i], xlat_packet, &xlat_inst[i]);
578 c = xlat_find(internal_xlat[i]);
579 rad_assert(c != NULL);
584 * New name: "control"
586 xlat_register("control", xlat_packet, &xlat_inst[0]);
587 c = xlat_find("control");
588 rad_assert(c != NULL);
593 * Register xlat's for regexes.
596 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
598 xlat_register(buffer, xlat_regex, &xlat_inst[i]);
599 c = xlat_find(buffer);
600 rad_assert(c != NULL);
603 #endif /* HAVE_REGEX_H */
606 xlat_register("debug", xlat_debug, &xlat_inst[0]);
607 c = xlat_find("debug");
608 rad_assert(c != NULL);
611 xlat_register("md5", xlat_md5, &xlat_inst[0]);
612 c = xlat_find("md5");
613 rad_assert(c != NULL);
618 * If it already exists, replace the instance.
620 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
621 my_xlat.length = strlen(my_xlat.module);
622 c = rbtree_finddata(xlat_root, &my_xlat);
625 DEBUG("xlat_register: Cannot re-define internal xlat");
630 c->instance = instance;
635 * Doesn't exist. Create it.
637 c = rad_malloc(sizeof(*c));
638 memset(c, 0, sizeof(*c));
641 strlcpy(c->module, module, sizeof(c->module));
642 c->length = strlen(c->module);
643 c->instance = instance;
645 rbtree_insert(xlat_root, c);
651 * Unregister an xlat function.
653 * We can only have one function to call per name, so the
654 * passing of "func" here is extraneous.
656 void xlat_unregister(const char *module, RAD_XLAT_FUNC func)
661 func = func; /* -Wunused */
665 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
666 my_xlat.length = strlen(my_xlat.module);
668 node = rbtree_find(xlat_root, &my_xlat);
671 rbtree_delete(xlat_root, node);
675 * De-register all xlat functions,
676 * used mainly for debugging.
680 rbtree_free(xlat_root);
685 * Decode an attribute name into a string.
687 static int decode_attribute(const char **from, char **to, int freespace,
689 RADIUS_ESCAPE_STRING func)
692 char *xlat_name, *xlat_string;
693 char *p, *q, *l, *next = NULL;
704 * Copy the input string to an intermediate buffer where
707 varlen = rad_copy_variable(buffer, *from);
709 RDEBUG2("Badly formatted variable: %s", *from);
715 * Kill the %{} around the data we are looking for.
718 p[varlen - 1] = '\0'; /* */
726 * Handle %{%{foo}:-%{bar}}, which is useful, too.
728 * Did I mention that this parser is garbage?
730 if ((p[0] == '%') && (p[1] == '{')) {
735 * 'p' is after the start of 'buffer', so we can
738 len1 = rad_copy_variable(buffer, p);
740 RDEBUG2("Badly formatted variable: %s", p);
745 * They did %{%{foo}}, which is stupid, but allowed.
748 RDEBUG2("Improperly nested variable; %%{%s}", p);
753 * It SHOULD be %{%{foo}:-%{bar}}. If not, it's
756 if ((p[len1] != ':') || (p[len1 + 1] != '-')) {
757 RDEBUG2("No trailing :- after variable at %s", p);
762 * Parse the second bit. The second bit can be
763 * either %{foo}, or a string "foo", or a string
764 * 'foo', or just a bare word: foo
767 l = buffer + len1 + 1;
769 if ((p[0] == '%') && (p[1] == '{')) {
770 len2 = rad_copy_variable(l, p);
773 RDEBUG2("Invalid text after :- at %s", p);
779 } else if ((p[0] == '"') || p[0] == '\'') {
780 getstring(&p, l, strlen(l));
787 * Expand the first one. If we did, exit the
790 retlen = radius_xlat(q, freespace, buffer, request, func);
796 RDEBUG2("\t... expanding second conditional");
798 * Expand / copy the second string if required.
801 retlen = radius_xlat(q, freespace, l,
807 strlcpy(q, l, freespace);
812 * Else the output is an empty string.
818 * See if we're supposed to expand a module name.
821 for (l = p; *l != '\0'; l++) {
828 xlat_name = p; /* start of name */
835 * Module names can't have spaces.
837 if ((*l == ' ') || (*l == '\t')) break;
841 * %{name} is a simple attribute reference,
842 * or regex reference.
845 xlat_name = xlat_string = p;
850 * Maybe it's the old-style %{foo:-bar}
853 RDEBUG2("WARNING: Deprecated conditional expansion \":-\". See \"man unlang\" for details");
856 xlat_string = xlat_name;
862 * FIXME: For backwards "WTF" compatibility, check for
863 * {...}, (after the :), and copy that, too.
866 /* module name, followed by (possibly) per-module string */
870 if ((c = xlat_find(xlat_name)) != NULL) {
871 if (!c->internal) RDEBUG3("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
872 c->module, xlat_string);
873 retlen = c->do_xlat(c->instance, request, xlat_string,
877 snprintf(q, freespace, "%d", retlen);
883 * Expand the second bit.
885 RDEBUG2("\t... expanding second conditional");
886 retlen = radius_xlat(q, freespace, next, request, func);
892 * No attribute by that name, return an error.
894 RDEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
904 * If the caller doesn't pass xlat an escape function, then
905 * we use this one. It simplifies the coding, as the check for
906 * func == NULL only happens once.
908 static size_t xlat_copy(char *out, size_t outlen, const char *in)
910 int freespace = outlen;
912 rad_assert(outlen > 0);
914 while ((*in) && (freespace > 1)) {
918 * FIXME: Do escaping of bad stuff!
926 return (outlen - freespace); /* count does not include NUL */
930 * Replace %<whatever> in a string.
932 * See 'doc/variables.txt' for more information.
934 int radius_xlat(char *out, int outlen, const char *fmt,
935 REQUEST *request, RADIUS_ESCAPE_STRING func)
937 int c, len, freespace;
943 char tmpdt[40]; /* For temporary storing of dates */
949 if (!fmt || !out || !request) return 0;
952 * Ensure that we always have an escaping function.
961 /* Calculate freespace in output */
962 freespace = outlen - (q - out);
967 if ((c != '%') && (c != '$') && (c != '\\')) {
969 * We check if we're inside an open brace. If we are
970 * then we assume this brace is NOT literal, but is
971 * a closing brace and apply it
973 if ((c == '}') && openbraces) {
983 * There's nothing after this character, copy
984 * the last '%' or "$' or '\\' over to the output
1010 } else if (c == '%') switch(*p) {
1013 if (decode_attribute(&p, &q, freespace, request, func) < 0) return 0;
1019 case 'a': /* Protocol: */
1020 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL),PW_TYPE_INTEGER, func);
1023 case 'c': /* Callback-Number */
1024 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER),PW_TYPE_STRING, func);
1027 case 'd': /* request day */
1028 TM = localtime_r(&request->timestamp, &s_TM);
1029 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
1031 strlcpy(q, tmpdt, freespace);
1036 case 'f': /* Framed IP address */
1037 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS),PW_TYPE_IPADDR, func);
1040 case 'i': /* Calling station ID */
1041 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID),PW_TYPE_STRING, func);
1044 case 'l': /* request timestamp */
1045 snprintf(tmpdt, sizeof(tmpdt), "%lu",
1046 (unsigned long) request->timestamp);
1047 strlcpy(q,tmpdt,freespace);
1051 case 'm': /* request month */
1052 TM = localtime_r(&request->timestamp, &s_TM);
1053 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
1055 strlcpy(q, tmpdt, freespace);
1060 case 'n': /* NAS IP address */
1061 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS),PW_TYPE_IPADDR, func);
1064 case 'p': /* Port number */
1065 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT),PW_TYPE_INTEGER, func);
1068 case 's': /* Speed */
1069 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO),PW_TYPE_STRING, func);
1072 case 't': /* request timestamp */
1073 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
1074 nl = strchr(tmpdt, '\n');
1076 strlcpy(q, tmpdt, freespace);
1080 case 'u': /* User name */
1081 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME),PW_TYPE_STRING, func);
1084 case 'A': /* radacct_dir */
1085 strlcpy(q,radacct_dir,freespace);
1089 case 'C': /* ClientName */
1090 strlcpy(q,request->client->shortname,freespace);
1094 case 'D': /* request date */
1095 TM = localtime_r(&request->timestamp, &s_TM);
1096 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
1098 strlcpy(q, tmpdt, freespace);
1103 case 'H': /* request hour */
1104 TM = localtime_r(&request->timestamp, &s_TM);
1105 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
1107 strlcpy(q, tmpdt, freespace);
1112 case 'L': /* radlog_dir */
1113 strlcpy(q,radlog_dir,freespace);
1118 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU),PW_TYPE_INTEGER, func);
1121 case 'R': /* radius_dir */
1122 strlcpy(q,radius_dir,freespace);
1126 case 'S': /* request timestamp in SQL format*/
1127 TM = localtime_r(&request->timestamp, &s_TM);
1128 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1130 strlcpy(q, tmpdt, freespace);
1135 case 'T': /* request timestamp */
1136 TM = localtime_r(&request->timestamp, &s_TM);
1137 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1139 strlcpy(q, tmpdt, freespace);
1144 case 'U': /* Stripped User name */
1145 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME),PW_TYPE_STRING, func);
1148 case 'V': /* Request-Authenticator */
1149 strlcpy(q,"Verified",freespace);
1153 case 'Y': /* request year */
1154 TM = localtime_r(&request->timestamp, &s_TM);
1155 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1157 strlcpy(q, tmpdt, freespace);
1162 case 'Z': /* Full request pairs except password */
1163 tmp = request->packet->vps;
1164 while (tmp && (freespace > 3)) {
1165 if (tmp->attribute != PW_USER_PASSWORD) {
1167 len = vp_prints(q, freespace - 2, tmp);
1169 freespace -= (len + 2);
1177 RDEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1178 if (freespace > 2) {
1187 RDEBUG2("\texpand: %s -> %s", fmt, out);