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/rad_assert.h>
33 typedef struct xlat_t {
34 char module[MAX_STRING_LEN];
37 RAD_XLAT_FUNC do_xlat;
38 int internal; /* not allowed to re-define these */
41 static rbtree_t *xlat_root = NULL;
44 * Define all xlat's in the structure.
46 static const char * const internal_xlat[] = {"check",
55 #if REQUEST_MAX_REGEX > 8
56 #error Please fix the following line
58 static const int xlat_inst[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; /* up to 8 for regex */
62 * Convert the value on a VALUE_PAIR to string
64 static int valuepair2str(char * out,int outlen,VALUE_PAIR * pair,
65 int type, RADIUS_ESCAPE_STRING func)
67 char buffer[MAX_STRING_LEN * 4];
70 vp_prints_value(buffer, sizeof(buffer), pair, -1);
71 return func(out, outlen, buffer);
76 strlcpy(out,"_",outlen);
78 case PW_TYPE_INTEGER :
79 strlcpy(out,"0",outlen);
82 strlcpy(out,"?.?.?.?",outlen);
84 case PW_TYPE_IPV6ADDR :
85 strlcpy(out,":?:",outlen);
88 strlcpy(out,"0",outlen);
91 strlcpy(out,"unknown_type",outlen);
98 * Dynamically translate for check:, request:, reply:, etc.
100 static size_t xlat_packet(void *instance, REQUEST *request,
101 char *fmt, char *out, size_t outlen,
102 RADIUS_ESCAPE_STRING func)
106 VALUE_PAIR *vps = NULL;
107 RADIUS_PACKET *packet = NULL;
109 switch (*(int*) instance) {
111 vps = request->config_items;
115 vps = request->packet->vps;
116 packet = request->packet;
120 vps = request->reply->vps;
121 packet = request->reply;
125 if (request->proxy) vps = request->proxy->vps;
126 packet = request->proxy;
130 if (request->proxy_reply) vps = request->proxy_reply->vps;
131 packet = request->proxy_reply;
135 if (request->parent) {
136 vps = request->parent->packet->vps;
137 packet = request->parent->packet;
142 if (request->parent && request->parent->reply) {
143 vps = request->parent->reply->vps;
144 packet = request->parent->reply;
153 * The "format" string is the attribute name.
155 da = dict_attrbyname(fmt);
158 const char *p = strchr(fmt, '[');
162 if (strlen(fmt) > sizeof(buffer)) return 0;
164 strlcpy(buffer, fmt, p - fmt + 1);
166 da = dict_attrbyname(buffer);
170 * %{Attribute-Name[#]} returns the count of
171 * attributes of that name in the list.
173 if ((p[1] == '#') && (p[2] == ']')) {
176 for (vp = pairfind(vps, da->attr);
178 vp = pairfind(vp->next, da->attr)) {
181 snprintf(out, outlen, "%d", count);
186 * %{Attribute-Name[*]} returns ALL of the
187 * the attributes, separated by a newline.
189 if ((p[1] == '*') && (p[2] == ']')) {
192 for (vp = pairfind(vps, da->attr);
194 vp = pairfind(vp->next, da->attr)) {
195 count = valuepair2str(out, outlen - 1, vp, da->type, func);
196 rad_assert(count <= outlen);
198 outlen -= (count + 1);
203 if (outlen == 0) break;
214 p += 1 + strspn(p + 1, "0123456789");
216 DEBUG2("xlat: Invalid array reference in string at %s %s",
222 * Find the N'th value.
224 for (vp = pairfind(vps, da->attr);
226 vp = pairfind(vp->next, da->attr)) {
227 if (count == 0) break;
232 * Non-existent array reference.
236 return valuepair2str(out, outlen, vp, da->type, func);
239 vp = pairfind(vps, da->attr);
242 * Some "magic" handlers, which are never in VP's, but
243 * which are in the packet.
245 * FIXME: We should really do this in a more
251 memset(&localvp, 0, sizeof(localvp));
258 dval = dict_valbyattr(da->attr, packet->code);
260 snprintf(out, outlen, "%s", dval->name);
262 snprintf(out, outlen, "%d", packet->code);
268 case PW_CLIENT_SHORTNAME:
269 if (request->client && request->client->shortname) {
270 strlcpy(out, request->client->shortname, outlen);
272 strlcpy(out, "<UNKNOWN-CLIENT>", outlen);
276 case PW_CLIENT_IP_ADDRESS: /* the same as below */
277 case PW_PACKET_SRC_IP_ADDRESS:
278 if (packet->src_ipaddr.af != AF_INET) {
281 localvp.attribute = da->attr;
282 localvp.vp_ipaddr = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
285 case PW_PACKET_DST_IP_ADDRESS:
286 if (packet->dst_ipaddr.af != AF_INET) {
289 localvp.attribute = da->attr;
290 localvp.vp_ipaddr = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
293 case PW_PACKET_SRC_PORT:
294 localvp.attribute = da->attr;
295 localvp.vp_integer = packet->src_port;
298 case PW_PACKET_DST_PORT:
299 localvp.attribute = da->attr;
300 localvp.vp_integer = packet->dst_port;
303 case PW_PACKET_AUTHENTICATION_VECTOR:
304 localvp.attribute = da->attr;
305 memcpy(localvp.vp_strvalue, packet->vector,
306 sizeof(packet->vector));
307 localvp.length = sizeof(packet->vector);
311 * Authorization, accounting, etc.
313 case PW_REQUEST_PROCESSING_STAGE:
314 if (request->component) {
315 strlcpy(out, request->component, outlen);
317 strlcpy(out, "server_core", outlen);
321 case PW_PACKET_SRC_IPV6_ADDRESS:
322 if (packet->src_ipaddr.af != AF_INET6) {
325 localvp.attribute = da->attr;
326 memcpy(localvp.vp_strvalue,
327 &packet->src_ipaddr.ipaddr.ip6addr,
328 sizeof(packet->src_ipaddr.ipaddr.ip6addr));
331 case PW_PACKET_DST_IPV6_ADDRESS:
332 if (packet->dst_ipaddr.af != AF_INET6) {
335 localvp.attribute = da->attr;
336 memcpy(localvp.vp_strvalue,
337 &packet->dst_ipaddr.ipaddr.ip6addr,
338 sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
341 case PW_VIRTUAL_SERVER:
342 if (!request->server) return 0;
344 snprintf(out, outlen, "%s", request->server);
348 case PW_MODULE_RETURN_CODE:
349 localvp.attribute = da->attr;
352 * See modcall.c for a bit of a hack.
354 localvp.vp_integer = request->simul_max;
358 return 0; /* not found */
362 localvp.type = da->type;
363 return valuepair2str(out, outlen, &localvp,
373 if (!vps) return 0; /* silently fail */
376 * Convert the VP to a string, and return it.
378 return valuepair2str(out, outlen, vp, da->type, func);
383 * Pull %{0} to %{8} out of the packet.
385 static size_t xlat_regex(void *instance, REQUEST *request,
386 char *fmt, char *out, size_t outlen,
387 RADIUS_ESCAPE_STRING func)
392 * We cheat: fmt is "0" to "8", but those numbers
393 * are already in the "instance".
395 fmt = fmt; /* -Wunused */
396 func = func; /* -Wunused FIXME: do escaping? */
398 regex = request_data_reference(request, request,
399 REQUEST_DATA_REGEX | *(int *)instance);
400 if (!regex) return 0;
403 * Copy UP TO "freespace" bytes, including
406 strlcpy(out, regex, outlen);
409 #endif /* HAVE_REGEX_H */
413 * Compare two xlat_t structs, based ONLY on the module name.
415 static int xlat_cmp(const void *a, const void *b)
417 if (((const xlat_t *)a)->length != ((const xlat_t *)b)->length) {
418 return ((const xlat_t *)a)->length - ((const xlat_t *)b)->length;
421 return memcmp(((const xlat_t *)a)->module,
422 ((const xlat_t *)b)->module,
423 ((const xlat_t *)a)->length);
428 * find the appropriate registered xlat function.
430 static xlat_t *xlat_find(const char *module)
435 * Look for dictionary attributes first.
437 if ((dict_attrbyname(module) != NULL) ||
438 (strchr(module, '[') != NULL)) {
442 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
443 my_xlat.length = strlen(my_xlat.module);
445 return rbtree_finddata(xlat_root, &my_xlat);
450 * Register an xlat function.
452 int xlat_register(const char *module, RAD_XLAT_FUNC func, void *instance)
457 if ((module == NULL) || (strlen(module) == 0)) {
458 DEBUG("xlat_register: Invalid module name");
463 * First time around, build up the tree...
465 * FIXME: This code should be hoisted out of this function,
466 * and into a global "initialization". But it isn't critical...
474 xlat_root = rbtree_create(xlat_cmp, free, 0);
476 DEBUG("xlat_register: Failed to create tree.");
481 * Register the internal packet xlat's.
483 for (i = 0; internal_xlat[i] != NULL; i++) {
484 xlat_register(internal_xlat[i], xlat_packet, &xlat_inst[i]);
485 c = xlat_find(internal_xlat[i]);
486 rad_assert(c != NULL);
491 * New name: "control"
493 xlat_register("control", xlat_packet, &xlat_inst[0]);
494 c = xlat_find("control");
495 rad_assert(c != NULL);
500 * Register xlat's for regexes.
503 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
505 xlat_register(buffer, xlat_regex, &xlat_inst[i]);
506 c = xlat_find(buffer);
507 rad_assert(c != NULL);
510 #endif /* HAVE_REGEX_H */
514 * If it already exists, replace the instance.
516 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
517 my_xlat.length = strlen(my_xlat.module);
518 c = rbtree_finddata(xlat_root, &my_xlat);
521 DEBUG("xlat_register: Cannot re-define internal xlat");
526 c->instance = instance;
531 * Doesn't exist. Create it.
533 c = rad_malloc(sizeof(*c));
534 memset(c, 0, sizeof(*c));
537 strlcpy(c->module, module, sizeof(c->module));
538 c->length = strlen(c->module);
539 c->instance = instance;
541 rbtree_insert(xlat_root, c);
547 * Unregister an xlat function.
549 * We can only have one function to call per name, so the
550 * passing of "func" here is extraneous.
552 void xlat_unregister(const char *module, RAD_XLAT_FUNC func)
557 func = func; /* -Wunused */
561 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
562 my_xlat.length = strlen(my_xlat.module);
564 node = rbtree_find(xlat_root, &my_xlat);
567 rbtree_delete(xlat_root, node);
571 * De-register all xlat functions,
572 * used mainly for debugging.
576 rbtree_free(xlat_root);
581 * Decode an attribute name into a string.
583 static void decode_attribute(const char **from, char **to, int freespace,
584 int *open_p, REQUEST *request,
585 RADIUS_ESCAPE_STRING func)
589 char *xlat_string = NULL; /* can be large */
590 int free_xlat_string = FALSE;
593 int found=0, retlen=0;
594 int openbraces = *open_p;
605 * Skip the '{' at the front of 'p'
606 * Increment open braces
617 * Handle %{%{foo}:-%{bar}}, which is useful, too.
619 * Did I mention that this parser is garbage?
621 if ((p[0] == '%') && (p[1] == '{')) {
623 * This is really bad, but it works.
626 size_t mylen = strlen(p);
627 char *first = rad_malloc(mylen);
628 char *second = rad_malloc(mylen);
631 len1 = rad_copy_variable(first, p);
633 DEBUG2("Badly formatted variable: %s", p);
637 if ((p[len1] != ':') || (p[len1 + 1] != '-')) {
638 DEBUG2("No trailing :- after variable at %s", p);
644 if ((p[0] == '%') && (p[1] == '{')) {
645 len2 = rad_copy_variable(second, p);
649 DEBUG2("Invalid text after :- at %s", p);
654 } else if ((p[0] == '"') || p[0] == '\'') {
655 getstring(&p, second, mylen);
660 while (*p && (*p != '}')) {
667 DEBUG2("Failed to find trailing '}' in string");
671 mylen = radius_xlat(q, freespace, first, request, func);
678 strlcpy(q, second, freespace);
681 mylen = radius_xlat(q, freespace, second,
690 * Else the output is an empty string.
700 * First, copy the xlat key name to one buffer
702 while (*p && (*p != '}') && (*p != ':')) {
705 if (pa >= (xlat_name + sizeof(xlat_name) - 1)) {
707 * Skip to the end of the input
710 DEBUG("xlat: Module name is too long in string %%%s",
718 DEBUG("xlat: Invalid syntax in %s", *from);
721 * %{name} is a simple attribute reference,
722 * or regex reference.
724 } else if (*p == '}') {
726 rad_assert(openbraces == *open_p);
729 xlat_string = xlat_name;
732 } else if ((p[0] == ':') && (p[1] == '-')) { /* handle ':- */
733 DEBUG2("WARNING: Deprecated conditional expansion \":-\". See \"man unlang\" for details");
735 xlat_string = xlat_name;
738 } else { /* module name, followed by per-module string */
740 int delimitbrace = *open_p;
742 rad_assert(*p == ':');
743 p++; /* skip the ':' */
746 * If there's a brace immediately following the colon,
747 * then we've chosen to delimite the per-module string,
748 * so keep track of that.
751 delimitbrace = openbraces;
756 xlat_string = rad_malloc(strlen(p) + 1); /* always returns */
757 free_xlat_string = TRUE;
761 * Copy over the rest of the string, which is per-module
764 while (*p && !stop) {
768 * What the heck is this supposed
777 if (!spaces && p[1] == '-') {
786 * This is pretty hokey... we
787 * should use the functions in
797 if (openbraces == delimitbrace) {
819 * Now check to see if we're at the end of the string
820 * we were sent. If we're not, check for :-
822 if (openbraces == delimitbrace) {
823 if (p[0] == ':' && p[1] == '-') {
829 * Look up almost everything in the new tree of xlat
830 * functions. This makes it a little quicker...
833 if ((c = xlat_find(xlat_name)) != NULL) {
834 if (!c->internal) DEBUG3("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
835 c->module, xlat_string);
836 retlen = c->do_xlat(c->instance, request, xlat_string,
838 /* If retlen is 0, treat it as not found */
839 if (retlen > 0) found = 1;
844 * No attribute by that name, return an error.
846 DEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
852 * Skip to last '}' if attr is found
853 * The rest of the stuff within the braces is
854 * useless if we found what we need
858 snprintf(q, freespace, "%d", retlen);
864 while((*p != '\0') && (openbraces > *open_p)) {
866 * Handle escapes outside of the loop.
871 p++; /* get & ignore next character */
890 p++; /* skip the character */
895 if (free_xlat_string) free(xlat_string);
897 *open_p = openbraces;
903 * If the caller doesn't pass xlat an escape function, then
904 * we use this one. It simplifies the coding, as the check for
905 * func == NULL only happens once.
907 static size_t xlat_copy(char *out, size_t outlen, const char *in)
909 int freespace = outlen;
911 rad_assert(outlen > 0);
913 while ((*in) && (freespace > 1)) {
917 * FIXME: Do escaping of bad stuff!
925 return (outlen - freespace); /* count does not include NUL */
929 * Replace %<whatever> in a string.
931 * See 'doc/variables.txt' for more information.
933 int radius_xlat(char *out, int outlen, const char *fmt,
934 REQUEST *request, RADIUS_ESCAPE_STRING func)
936 int c, len, freespace;
942 char tmpdt[40]; /* For temporary storing of dates */
948 if (!fmt || !out || !request) return 0;
951 * Ensure that we always have an escaping function.
960 /* Calculate freespace in output */
961 freespace = outlen - (q - out);
966 if ((c != '%') && (c != '$') && (c != '\\')) {
968 * We check if we're inside an open brace. If we are
969 * then we assume this brace is NOT literal, but is
970 * a closing brace and apply it
972 if ((c == '}') && openbraces) {
982 * There's nothing after this character, copy
983 * the last '%' or "$' or '\\' over to the output
1009 } else if (c == '%') switch(*p) {
1011 decode_attribute(&p, &q, freespace, &openbraces, request, func);
1017 case 'a': /* Protocol: */
1018 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL),PW_TYPE_INTEGER, func);
1021 case 'c': /* Callback-Number */
1022 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER),PW_TYPE_STRING, func);
1025 case 'd': /* request day */
1026 TM = localtime_r(&request->timestamp, &s_TM);
1027 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
1029 strlcpy(q, tmpdt, freespace);
1034 case 'f': /* Framed IP address */
1035 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS),PW_TYPE_IPADDR, func);
1038 case 'i': /* Calling station ID */
1039 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID),PW_TYPE_STRING, func);
1042 case 'l': /* request timestamp */
1043 snprintf(tmpdt, sizeof(tmpdt), "%lu",
1044 (unsigned long) request->received.tv_sec);
1045 strlcpy(q,tmpdt,freespace);
1049 case 'm': /* request month */
1050 TM = localtime_r(&request->timestamp, &s_TM);
1051 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
1053 strlcpy(q, tmpdt, freespace);
1058 case 'n': /* NAS IP address */
1059 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS),PW_TYPE_IPADDR, func);
1062 case 'p': /* Port number */
1063 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT),PW_TYPE_INTEGER, func);
1066 case 's': /* Speed */
1067 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO),PW_TYPE_STRING, func);
1070 case 't': /* request timestamp */
1071 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
1072 nl = strchr(tmpdt, '\n');
1074 strlcpy(q, tmpdt, freespace);
1078 case 'u': /* User name */
1079 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME),PW_TYPE_STRING, func);
1082 case 'A': /* radacct_dir */
1083 strlcpy(q,radacct_dir,freespace);
1087 case 'C': /* ClientName */
1088 strlcpy(q,request->client->shortname,freespace);
1092 case 'D': /* request date */
1093 TM = localtime_r(&request->timestamp, &s_TM);
1094 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
1096 strlcpy(q, tmpdt, freespace);
1101 case 'H': /* request hour */
1102 TM = localtime_r(&request->timestamp, &s_TM);
1103 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
1105 strlcpy(q, tmpdt, freespace);
1110 case 'L': /* radlog_dir */
1111 strlcpy(q,radlog_dir,freespace);
1116 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU),PW_TYPE_INTEGER, func);
1119 case 'R': /* radius_dir */
1120 strlcpy(q,radius_dir,freespace);
1124 case 'S': /* request timestamp in SQL format*/
1125 TM = localtime_r(&request->timestamp, &s_TM);
1126 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1128 strlcpy(q, tmpdt, freespace);
1133 case 'T': /* request timestamp */
1134 TM = localtime_r(&request->timestamp, &s_TM);
1135 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1137 strlcpy(q, tmpdt, freespace);
1142 case 'U': /* Stripped User name */
1143 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME),PW_TYPE_STRING, func);
1146 case 'V': /* Request-Authenticator */
1147 strlcpy(q,"Verified",freespace);
1151 case 'Y': /* request year */
1152 TM = localtime_r(&request->timestamp, &s_TM);
1153 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1155 strlcpy(q, tmpdt, freespace);
1160 case 'Z': /* Full request pairs except password */
1161 tmp = request->packet->vps;
1162 while (tmp && (freespace > 3)) {
1163 if (tmp->attribute != PW_USER_PASSWORD) {
1165 len = vp_prints(q, freespace - 2, tmp);
1167 freespace -= (len + 2);
1175 DEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1176 if (freespace > 2) {
1185 DEBUG2("\texpand: %s -> %s", fmt, out);