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 memset(&localvp, 0, sizeof(localvp));
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 */
380 * Compare two xlat_t structs, based ONLY on the module name.
382 static int xlat_cmp(const void *a, const void *b)
384 if (((const xlat_t *)a)->length != ((const xlat_t *)b)->length) {
385 return ((const xlat_t *)a)->length - ((const xlat_t *)b)->length;
388 return memcmp(((const xlat_t *)a)->module,
389 ((const xlat_t *)b)->module,
390 ((const xlat_t *)a)->length);
395 * find the appropriate registered xlat function.
397 static const xlat_t *xlat_find(const char *module)
402 * Look for dictionary attributes first.
404 if ((dict_attrbyname(module) != NULL) ||
405 (strchr(module, '[') != NULL)) {
406 static const xlat_t dict_xlat = {
417 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
418 my_xlat.length = strlen(my_xlat.module);
420 return rbtree_finddata(xlat_root, &my_xlat);
425 * Register an xlat function.
427 int xlat_register(const char *module, RAD_XLAT_FUNC func, void *instance)
432 if ((module == NULL) || (strlen(module) == 0)) {
433 DEBUG("xlat_register: Invalid module name");
438 * First time around, build up the tree...
440 * FIXME: This code should be hoisted out of this function,
441 * and into a global "initialization". But it isn't critical...
449 xlat_root = rbtree_create(xlat_cmp, free, 0);
451 DEBUG("xlat_register: Failed to create tree.");
456 * Register the internal packet xlat's.
458 for (i = 0; internal_xlat[i] != NULL; i++) {
459 xlat_register(internal_xlat[i], xlat_packet, &xlat_inst[i]);
460 c = xlat_find(internal_xlat[i]);
461 rad_assert(c != NULL);
466 * New name: "control"
468 xlat_register("control", xlat_packet, &xlat_inst[0]);
469 c = xlat_find("control");
470 rad_assert(c != NULL);
475 * Register xlat's for regexes.
478 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
480 xlat_register(buffer, xlat_regex, &xlat_inst[i]);
481 c = xlat_find(buffer);
482 rad_assert(c != NULL);
485 #endif /* HAVE_REGEX_H */
489 * If it already exists, replace the instance.
491 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
492 my_xlat.length = strlen(my_xlat.module);
493 c = rbtree_finddata(xlat_root, &my_xlat);
496 DEBUG("xlat_register: Cannot re-define internal xlat");
501 c->instance = instance;
506 * Doesn't exist. Create it.
508 c = rad_malloc(sizeof(*c));
509 memset(c, 0, sizeof(*c));
512 strlcpy(c->module, module, sizeof(c->module));
513 c->length = strlen(c->module);
514 c->instance = instance;
516 rbtree_insert(xlat_root, c);
522 * Unregister an xlat function.
524 * We can only have one function to call per name, so the
525 * passing of "func" here is extraneous.
527 void xlat_unregister(const char *module, RAD_XLAT_FUNC func)
532 func = func; /* -Wunused */
536 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
537 my_xlat.length = strlen(my_xlat.module);
539 node = rbtree_find(xlat_root, &my_xlat);
542 rbtree_delete(xlat_root, node);
546 * De-register all xlat functions,
547 * used mainly for debugging.
551 rbtree_free(xlat_root);
556 * Decode an attribute name into a string.
558 static void decode_attribute(const char **from, char **to, int freespace,
559 int *open_p, REQUEST *request,
560 RADIUS_ESCAPE_STRING func)
564 char *xlat_string = NULL; /* can be large */
565 int free_xlat_string = FALSE;
568 int found=0, retlen=0;
569 int openbraces = *open_p;
580 * Skip the '{' at the front of 'p'
581 * Increment open braces
592 * First, copy the xlat key name to one buffer
594 while (*p && (*p != '}') && (*p != ':')) {
597 if (pa >= (xlat_name + sizeof(xlat_name) - 1)) {
599 * Skip to the end of the input
602 DEBUG("xlat: Module name is too long in string %%%s",
610 DEBUG("xlat: Invalid syntax in %s", *from);
613 * %{name} is a simple attribute reference,
614 * or regex reference.
616 } else if (*p == '}') {
618 rad_assert(openbraces == *open_p);
621 xlat_string = xlat_name;
624 } else if (p[1] == '-') { /* handle ':- */
626 xlat_string = xlat_name;
629 } else { /* module name, followed by per-module string */
631 int delimitbrace = *open_p;
633 rad_assert(*p == ':');
634 p++; /* skip the ':' */
637 * If there's a brace immediately following the colon,
638 * then we've chosen to delimite the per-module string,
639 * so keep track of that.
642 delimitbrace = openbraces;
647 xlat_string = rad_malloc(strlen(p) + 1); /* always returns */
648 free_xlat_string = TRUE;
652 * Copy over the rest of the string, which is per-module
655 while (*p && !stop) {
659 * What the heck is this supposed
668 if (!spaces && p[1] == '-') {
675 * This is pretty hokey... we
676 * should use the functions in
686 if (openbraces == delimitbrace) {
708 * Now check to see if we're at the end of the string
709 * we were sent. If we're not, check for :-
711 if (openbraces == delimitbrace) {
712 if (p[0] == ':' && p[1] == '-') {
718 * Look up almost everything in the new tree of xlat
719 * functions. This makes it a little quicker...
722 if ((c = xlat_find(xlat_name)) != NULL) {
723 if (!c->internal) DEBUG3("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
724 c->module, xlat_string);
725 retlen = c->do_xlat(c->instance, request, xlat_string,
727 /* If retlen is 0, treat it as not found */
728 if (retlen > 0) found = 1;
732 * No attribute by that name, return an error.
734 DEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
740 * Skip to last '}' if attr is found
741 * The rest of the stuff within the braces is
742 * useless if we found what we need
746 snprintf(q, freespace, "%d", retlen);
752 while((*p != '\0') && (openbraces > *open_p)) {
754 * Handle escapes outside of the loop.
759 p++; /* get & ignore next character */
778 p++; /* skip the character */
783 if (free_xlat_string) free(xlat_string);
785 *open_p = openbraces;
791 * If the caller doesn't pass xlat an escape function, then
792 * we use this one. It simplifies the coding, as the check for
793 * func == NULL only happens once.
795 static int xlat_copy(char *out, int outlen, const char *in)
797 int freespace = outlen;
799 rad_assert(outlen > 0);
801 while ((*in) && (freespace > 1)) {
805 * FIXME: Do escaping of bad stuff!
813 return (outlen - freespace); /* count does not include NUL */
817 * Replace %<whatever> in a string.
819 * See 'doc/variables.txt' for more information.
821 int radius_xlat(char *out, int outlen, const char *fmt,
822 REQUEST *request, RADIUS_ESCAPE_STRING func)
824 int c, len, freespace;
830 char tmpdt[40]; /* For temporary storing of dates */
836 if (!fmt || !out || !request) return 0;
839 * Ensure that we always have an escaping function.
848 /* Calculate freespace in output */
849 freespace = outlen - (q - out);
854 if ((c != '%') && (c != '$') && (c != '\\')) {
856 * We check if we're inside an open brace. If we are
857 * then we assume this brace is NOT literal, but is
858 * a closing brace and apply it
860 if ((c == '}') && openbraces) {
870 * There's nothing after this character, copy
871 * the last '%' or "$' or '\\' over to the output
897 } else if (c == '%') switch(*p) {
899 decode_attribute(&p, &q, freespace, &openbraces, request, func);
905 case 'a': /* Protocol: */
906 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL),PW_TYPE_INTEGER, func);
909 case 'c': /* Callback-Number */
910 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER),PW_TYPE_STRING, func);
913 case 'd': /* request day */
914 TM = localtime_r(&request->timestamp, &s_TM);
915 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
917 strlcpy(q, tmpdt, freespace);
922 case 'f': /* Framed IP address */
923 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS),PW_TYPE_IPADDR, func);
926 case 'i': /* Calling station ID */
927 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID),PW_TYPE_STRING, func);
930 case 'l': /* request timestamp */
931 snprintf(tmpdt, sizeof(tmpdt), "%lu",
932 (unsigned long) request->received.tv_sec);
933 strlcpy(q,tmpdt,freespace);
937 case 'm': /* request month */
938 TM = localtime_r(&request->timestamp, &s_TM);
939 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
941 strlcpy(q, tmpdt, freespace);
946 case 'n': /* NAS IP address */
947 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS),PW_TYPE_IPADDR, func);
950 case 'p': /* Port number */
951 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT),PW_TYPE_INTEGER, func);
954 case 's': /* Speed */
955 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO),PW_TYPE_STRING, func);
958 case 't': /* request timestamp */
959 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
960 nl = strchr(tmpdt, '\n');
962 strlcpy(q, tmpdt, freespace);
966 case 'u': /* User name */
967 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME),PW_TYPE_STRING, func);
970 case 'A': /* radacct_dir */
971 strlcpy(q,radacct_dir,freespace);
975 case 'C': /* ClientName */
976 strlcpy(q,client_name_old(&request->packet->src_ipaddr),freespace);
980 case 'D': /* request date */
981 TM = localtime_r(&request->timestamp, &s_TM);
982 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
984 strlcpy(q, tmpdt, freespace);
989 case 'H': /* request hour */
990 TM = localtime_r(&request->timestamp, &s_TM);
991 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
993 strlcpy(q, tmpdt, freespace);
998 case 'L': /* radlog_dir */
999 strlcpy(q,radlog_dir,freespace);
1004 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU),PW_TYPE_INTEGER, func);
1007 case 'R': /* radius_dir */
1008 strlcpy(q,radius_dir,freespace);
1012 case 'S': /* request timestamp in SQL format*/
1013 TM = localtime_r(&request->timestamp, &s_TM);
1014 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1016 strlcpy(q, tmpdt, freespace);
1021 case 'T': /* request timestamp */
1022 TM = localtime_r(&request->timestamp, &s_TM);
1023 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1025 strlcpy(q, tmpdt, freespace);
1030 case 'U': /* Stripped User name */
1031 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME),PW_TYPE_STRING, func);
1034 case 'V': /* Request-Authenticator */
1035 strlcpy(q,"Verified",freespace);
1039 case 'Y': /* request year */
1040 TM = localtime_r(&request->timestamp, &s_TM);
1041 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1043 strlcpy(q, tmpdt, freespace);
1048 case 'Z': /* Full request pairs except password */
1049 tmp = request->packet->vps;
1050 while (tmp && (freespace > 3)) {
1051 if (tmp->attribute != PW_USER_PASSWORD) {
1053 len = vp_prints(q, freespace - 2, tmp);
1055 freespace -= (len + 2);
1063 DEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1064 if (freespace > 2) {
1073 DEBUG2("\texpand: %s -> %s", fmt, out);