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",
53 #if REQUEST_MAX_REGEX > 8
54 #error Please fix the following line
56 static const int xlat_inst[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; /* up to 8 for regex */
60 * Convert the value on a VALUE_PAIR to string
62 static int valuepair2str(char * out,int outlen,VALUE_PAIR * pair,
63 int type, RADIUS_ESCAPE_STRING func)
65 char buffer[MAX_STRING_LEN * 4];
68 vp_prints_value(buffer, sizeof(buffer), pair, -1);
69 return func(out, outlen, buffer);
74 strlcpy(out,"_",outlen);
76 case PW_TYPE_INTEGER :
77 strlcpy(out,"0",outlen);
80 strlcpy(out,"?.?.?.?",outlen);
82 case PW_TYPE_IPV6ADDR :
83 strlcpy(out,":?:",outlen);
86 strlcpy(out,"0",outlen);
89 strlcpy(out,"unknown_type",outlen);
96 * Dynamically translate for check:, request:, reply:, etc.
98 static int xlat_packet(void *instance, REQUEST *request,
99 char *fmt, char *out, size_t outlen,
100 RADIUS_ESCAPE_STRING func)
104 VALUE_PAIR *vps = NULL;
105 RADIUS_PACKET *packet = NULL;
107 switch (*(int*) instance) {
109 vps = request->config_items;
113 vps = request->packet->vps;
114 packet = request->packet;
118 vps = request->reply->vps;
119 packet = request->reply;
123 if (request->proxy) vps = request->proxy->vps;
124 packet = request->proxy;
128 if (request->proxy_reply) vps = request->proxy_reply->vps;
129 packet = request->proxy_reply;
137 * The "format" string is the attribute name.
139 da = dict_attrbyname(fmt);
142 const char *p = strchr(fmt, '[');
146 if (strlen(fmt) > sizeof(buffer)) return 0;
148 strlcpy(buffer, fmt, p - fmt + 1);
150 da = dict_attrbyname(buffer);
154 * %{Attribute-Name[#]} returns the count of
155 * attributes of that name in the list.
157 if ((p[1] == '#') && (p[2] == ']')) {
160 for (vp = pairfind(vps, da->attr);
162 vp = pairfind(vp->next, da->attr)) {
165 snprintf(out, outlen, "%d", count);
170 * %{Attribute-Name[*]} returns ALL of the
171 * the attributes, separated by a newline.
173 if ((p[1] == '*') && (p[2] == ']')) {
176 for (vp = pairfind(vps, da->attr);
178 vp = pairfind(vp->next, da->attr)) {
179 count = valuepair2str(out, outlen - 1, vp, da->type, func);
180 rad_assert(count <= outlen);
182 outlen -= (count + 1);
187 if (outlen == 0) break;
198 p += 1 + strspn(p + 1, "0123456789");
200 DEBUG2("xlat: Invalid array reference in string at %s %s",
206 * Find the N'th value.
208 for (vp = pairfind(vps, da->attr);
210 vp = pairfind(vp->next, da->attr)) {
211 if (count == 0) break;
216 * Non-existent array reference.
220 return valuepair2str(out, outlen, vp, da->type, func);
223 vp = pairfind(vps, da->attr);
226 * Some "magic" handlers, which are never in VP's, but
227 * which are in the packet.
229 * FIXME: We should really do this in a more
235 localvp.vp_strvalue[0] = 0;
242 dval = dict_valbyattr(da->attr, packet->code);
244 snprintf(out, outlen, "%s", dval->name);
246 snprintf(out, outlen, "%d", packet->code);
252 case PW_CLIENT_IP_ADDRESS: /* the same as below */
253 case PW_PACKET_SRC_IP_ADDRESS:
254 if (packet->src_ipaddr.af != AF_INET) {
257 localvp.attribute = da->attr;
258 localvp.vp_ipaddr = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
261 case PW_PACKET_DST_IP_ADDRESS:
262 if (packet->dst_ipaddr.af != AF_INET) {
265 localvp.attribute = da->attr;
266 localvp.vp_ipaddr = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
269 case PW_PACKET_SRC_PORT:
270 localvp.attribute = da->attr;
271 localvp.vp_integer = packet->src_port;
274 case PW_PACKET_DST_PORT:
275 localvp.attribute = da->attr;
276 localvp.vp_integer = packet->dst_port;
279 case PW_PACKET_AUTHENTICATION_VECTOR:
280 localvp.attribute = da->attr;
281 memcpy(localvp.vp_strvalue, packet->vector,
282 sizeof(packet->vector));
283 localvp.length = sizeof(packet->vector);
287 * Authorization, accounting, etc.
289 case PW_REQUEST_PROCESSING_STAGE:
290 if (request->component) {
291 strlcpy(out, request->component, outlen);
293 strlcpy(out, "server_core", outlen);
297 case PW_PACKET_SRC_IPV6_ADDRESS:
298 if (packet->src_ipaddr.af != AF_INET6) {
301 localvp.attribute = da->attr;
302 memcpy(localvp.vp_strvalue,
303 &packet->src_ipaddr.ipaddr.ip6addr,
304 sizeof(packet->src_ipaddr.ipaddr.ip6addr));
307 case PW_PACKET_DST_IPV6_ADDRESS:
308 if (packet->dst_ipaddr.af != AF_INET6) {
311 localvp.attribute = da->attr;
312 memcpy(localvp.vp_strvalue,
313 &packet->dst_ipaddr.ipaddr.ip6addr,
314 sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
317 case PW_SERVER_IDENTITY:
318 if (!request->listener || !request->listener->identity) return 0;
320 snprintf(out, outlen, "%s", request->listener->identity);
325 return 0; /* not found */
329 localvp.type = da->type;
330 return valuepair2str(out, outlen, &localvp,
340 if (!vps) return 0; /* silently fail */
343 * Convert the VP to a string, and return it.
345 return valuepair2str(out, outlen, vp, da->type, func);
350 * Pull %{0} to %{8} out of the packet.
352 static int xlat_regex(void *instance, REQUEST *request,
353 char *fmt, char *out, size_t outlen,
354 RADIUS_ESCAPE_STRING func)
359 * We cheat: fmt is "0" to "8", but those numbers
360 * are already in the "instance".
362 fmt = fmt; /* -Wunused */
363 func = func; /* -Wunused FIXME: do escaping? */
365 regex = request_data_reference(request, request,
366 REQUEST_DATA_REGEX | *(int *)instance);
367 if (!regex) return 0;
370 * Copy UP TO "freespace" bytes, including
373 strlcpy(out, regex, outlen);
376 #endif /* HAVE_REGEX_H */
379 * Compare two xlat_t structs, based ONLY on the module name.
381 static int xlat_cmp(const void *a, const void *b)
383 if (((const xlat_t *)a)->length != ((const xlat_t *)b)->length) {
384 return ((const xlat_t *)a)->length - ((const xlat_t *)b)->length;
387 return memcmp(((const xlat_t *)a)->module,
388 ((const xlat_t *)b)->module,
389 ((const xlat_t *)a)->length);
394 * find the appropriate registered xlat function.
396 static const xlat_t *xlat_find(const char *module)
401 * Look for dictionary attributes first.
403 if ((dict_attrbyname(module) != NULL) ||
404 (strchr(module, '[') != NULL)) {
405 static const xlat_t dict_xlat = {
416 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
417 my_xlat.length = strlen(my_xlat.module);
419 return rbtree_finddata(xlat_root, &my_xlat);
424 * Register an xlat function.
426 int xlat_register(const char *module, RAD_XLAT_FUNC func, void *instance)
431 if ((module == NULL) || (strlen(module) == 0)) {
432 DEBUG("xlat_register: Invalid module name");
437 * First time around, build up the tree...
439 * FIXME: This code should be hoisted out of this function,
440 * and into a global "initialization". But it isn't critical...
448 xlat_root = rbtree_create(xlat_cmp, free, 0);
450 DEBUG("xlat_register: Failed to create tree.");
455 * Register the internal packet xlat's.
457 for (i = 0; internal_xlat[i] != NULL; i++) {
458 xlat_register(internal_xlat[i], xlat_packet, &xlat_inst[i]);
459 c = xlat_find(internal_xlat[i]);
460 rad_assert(c != NULL);
466 * Register xlat's for regexes.
469 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
471 xlat_register(buffer, xlat_regex, &xlat_inst[i]);
472 c = xlat_find(buffer);
473 rad_assert(c != NULL);
476 #endif /* HAVE_REGEX_H */
480 * If it already exists, replace the instance.
482 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
483 my_xlat.length = strlen(my_xlat.module);
484 c = rbtree_finddata(xlat_root, &my_xlat);
487 DEBUG("xlat_register: Cannot re-define internal xlat");
492 c->instance = instance;
497 * Doesn't exist. Create it.
499 c = rad_malloc(sizeof(xlat_t));
500 memset(c, 0, sizeof(*c));
503 strlcpy(c->module, module, sizeof(c->module));
504 c->length = strlen(c->module);
505 c->instance = instance;
507 rbtree_insert(xlat_root, c);
513 * Unregister an xlat function.
515 * We can only have one function to call per name, so the
516 * passing of "func" here is extraneous.
518 void xlat_unregister(const char *module, RAD_XLAT_FUNC func)
523 func = func; /* -Wunused */
527 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
528 my_xlat.length = strlen(my_xlat.module);
530 node = rbtree_find(xlat_root, &my_xlat);
533 rbtree_delete(xlat_root, node);
537 * De-register all xlat functions,
538 * used mainly for debugging.
542 rbtree_free(xlat_root);
547 * Decode an attribute name into a string.
549 static void decode_attribute(const char **from, char **to, int freespace,
550 int *open_p, REQUEST *request,
551 RADIUS_ESCAPE_STRING func)
555 char *xlat_string = NULL; /* can be large */
556 int free_xlat_string = FALSE;
559 int found=0, retlen=0;
560 int openbraces = *open_p;
571 * Skip the '{' at the front of 'p'
572 * Increment open braces
583 * First, copy the xlat key name to one buffer
585 while (*p && (*p != '}') && (*p != ':')) {
588 if (pa >= (xlat_name + sizeof(xlat_name) - 1)) {
590 * Skip to the end of the input
593 DEBUG("xlat: Module name is too long in string %%%s",
601 DEBUG("xlat: Invalid syntax in %s", *from);
604 * %{name} is a simple attribute reference,
605 * or regex reference.
607 } else if (*p == '}') {
609 rad_assert(openbraces == *open_p);
612 xlat_string = xlat_name;
615 } else if (p[1] == '-') { /* handle ':- */
617 xlat_string = xlat_name;
620 } else { /* module name, followed by per-module string */
622 int delimitbrace = *open_p;
624 rad_assert(*p == ':');
625 p++; /* skip the ':' */
628 * If there's a brace immediately following the colon,
629 * then we've chosen to delimite the per-module string,
630 * so keep track of that.
633 delimitbrace = openbraces;
638 xlat_string = rad_malloc(strlen(p) + 1); /* always returns */
639 free_xlat_string = TRUE;
643 * Copy over the rest of the string, which is per-module
646 while (*p && !stop) {
650 * What the heck is this supposed
659 if (!spaces && p[1] == '-') {
666 * This is pretty hokey... we
667 * should use the functions in
677 if (openbraces == delimitbrace) {
699 * Now check to see if we're at the end of the string
700 * we were sent. If we're not, check for :-
702 if (openbraces == delimitbrace) {
703 if (p[0] == ':' && p[1] == '-') {
709 * Look up almost everything in the new tree of xlat
710 * functions. This makes it a little quicker...
713 if ((c = xlat_find(xlat_name)) != NULL) {
714 if (!c->internal) DEBUG("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
715 c->module, xlat_string);
716 retlen = c->do_xlat(c->instance, request, xlat_string,
718 /* If retlen is 0, treat it as not found */
719 if (retlen > 0) found = 1;
723 * No attribute by that name, return an error.
725 DEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
731 * Skip to last '}' if attr is found
732 * The rest of the stuff within the braces is
733 * useless if we found what we need
737 snprintf(q, freespace, "%d", retlen);
743 while((*p != '\0') && (openbraces > *open_p)) {
745 * Handle escapes outside of the loop.
750 p++; /* get & ignore next character */
769 p++; /* skip the character */
774 if (free_xlat_string) free(xlat_string);
776 *open_p = openbraces;
782 * If the caller doesn't pass xlat an escape function, then
783 * we use this one. It simplifies the coding, as the check for
784 * func == NULL only happens once.
786 static int xlat_copy(char *out, int outlen, const char *in)
788 int freespace = outlen;
790 rad_assert(outlen > 0);
792 while ((*in) && (freespace > 1)) {
796 * FIXME: Do escaping of bad stuff!
804 return (outlen - freespace); /* count does not include NUL */
808 * Replace %<whatever> in a string.
810 * See 'doc/variables.txt' for more information.
812 int radius_xlat(char *out, int outlen, const char *fmt,
813 REQUEST *request, RADIUS_ESCAPE_STRING func)
815 int c, len, freespace;
821 char tmpdt[40]; /* For temporary storing of dates */
827 if (!fmt || !out || !request) return 0;
830 * Ensure that we always have an escaping function.
839 /* Calculate freespace in output */
840 freespace = outlen - (q - out);
845 if ((c != '%') && (c != '$') && (c != '\\')) {
847 * We check if we're inside an open brace. If we are
848 * then we assume this brace is NOT literal, but is
849 * a closing brace and apply it
851 if ((c == '}') && openbraces) {
861 * There's nothing after this character, copy
862 * the last '%' or "$' or '\\' over to the output
889 * Hmmm... ${User-Name} is a synonym for
894 } else if (c == '$') switch(*p) {
895 case '{': /* Attribute by Name */
896 decode_attribute(&p, &q, freespace, &openbraces, request, func);
903 } else if (c == '%') switch(*p) {
905 decode_attribute(&p, &q, freespace, &openbraces, request, func);
911 case 'a': /* Protocol: */
912 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL),PW_TYPE_INTEGER, func);
915 case 'c': /* Callback-Number */
916 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER),PW_TYPE_STRING, func);
919 case 'd': /* request day */
920 TM = localtime_r(&request->timestamp, &s_TM);
921 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
923 strlcpy(q, tmpdt, freespace);
928 case 'f': /* Framed IP address */
929 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS),PW_TYPE_IPADDR, func);
932 case 'i': /* Calling station ID */
933 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID),PW_TYPE_STRING, func);
936 case 'l': /* request timestamp */
937 snprintf(tmpdt, sizeof(tmpdt), "%lu",
938 (unsigned long) request->timestamp);
939 strlcpy(q,tmpdt,freespace);
943 case 'm': /* request month */
944 TM = localtime_r(&request->timestamp, &s_TM);
945 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
947 strlcpy(q, tmpdt, freespace);
952 case 'n': /* NAS IP address */
953 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS),PW_TYPE_IPADDR, func);
956 case 'p': /* Port number */
957 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT),PW_TYPE_INTEGER, func);
960 case 's': /* Speed */
961 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO),PW_TYPE_STRING, func);
964 case 't': /* request timestamp */
965 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
966 nl = strchr(tmpdt, '\n');
968 strlcpy(q, tmpdt, freespace);
972 case 'u': /* User name */
973 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME),PW_TYPE_STRING, func);
976 case 'A': /* radacct_dir */
977 strlcpy(q,radacct_dir,freespace);
981 case 'C': /* ClientName */
982 strlcpy(q,client_name_old(&request->packet->src_ipaddr),freespace);
986 case 'D': /* request date */
987 TM = localtime_r(&request->timestamp, &s_TM);
988 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
990 strlcpy(q, tmpdt, freespace);
995 case 'H': /* request hour */
996 TM = localtime_r(&request->timestamp, &s_TM);
997 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
999 strlcpy(q, tmpdt, freespace);
1004 case 'L': /* radlog_dir */
1005 strlcpy(q,radlog_dir,freespace);
1010 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU),PW_TYPE_INTEGER, func);
1013 case 'R': /* radius_dir */
1014 strlcpy(q,radius_dir,freespace);
1018 case 'S': /* request timestamp in SQL format*/
1019 TM = localtime_r(&request->timestamp, &s_TM);
1020 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1022 strlcpy(q, tmpdt, freespace);
1027 case 'T': /* request timestamp */
1028 TM = localtime_r(&request->timestamp, &s_TM);
1029 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1031 strlcpy(q, tmpdt, freespace);
1036 case 'U': /* Stripped User name */
1037 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME),PW_TYPE_STRING, func);
1040 case 'V': /* Request-Authenticator */
1041 if (request->packet->verified)
1042 strlcpy(q,"Verified",freespace);
1044 strlcpy(q,"None",freespace);
1048 case 'Y': /* request year */
1049 TM = localtime_r(&request->timestamp, &s_TM);
1050 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1052 strlcpy(q, tmpdt, freespace);
1057 case 'Z': /* Full request pairs except password */
1058 tmp = request->packet->vps;
1059 while (tmp && (freespace > 3)) {
1060 if (tmp->attribute != PW_USER_PASSWORD) {
1062 len = vp_prints(q, freespace - 2, tmp);
1064 freespace -= (len + 2);
1072 DEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1073 if (freespace > 2) {
1082 DEBUG2("radius_xlat: '%s'", out);