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_VIRTUAL_SERVER:
318 if (!request->server) return 0;
320 snprintf(out, outlen, "%s", request->server);
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 * Handle %{%{foo}:-%{bar}}, which is useful, too.
594 * Did I mention that this parser is garbage?
596 if ((p[0] == '%') && (p[1] == '{')) {
598 * This is really bad, but it works.
601 size_t mylen = strlen(p);
602 char *first = rad_malloc(mylen);
603 char *second = rad_malloc(mylen);
606 len1 = rad_copy_variable(first, p);
608 DEBUG2("Badly formatted variable: %s", p);
612 if ((p[len1] != ':') || (p[len1 + 1] != '-')) {
613 DEBUG2("No trailing :- after variable at %s", p);
619 if ((p[0] == '%') && (p[1] == '{')) {
620 len2 = rad_copy_variable(second, p);
624 DEBUG2("Invalid text after :- at %s", p);
629 } else if ((p[0] == '"') || p[0] == '\'') {
630 getstring(&p, second, mylen);
635 while (*p && (*p != '}')) {
642 DEBUG2("Failed to find trailing '}' in string");
646 mylen = radius_xlat(q, freespace, first, request, func);
656 strlcpy(q, second, freespace);
659 mylen = radius_xlat(q, freespace, second,
669 * Else the output is an empty string.
676 * First, copy the xlat key name to one buffer
678 while (*p && (*p != '}') && (*p != ':')) {
681 if (pa >= (xlat_name + sizeof(xlat_name) - 1)) {
683 * Skip to the end of the input
686 DEBUG("xlat: Module name is too long in string %%%s",
694 DEBUG("xlat: Invalid syntax in %s", *from);
697 * %{name} is a simple attribute reference,
698 * or regex reference.
700 } else if (*p == '}') {
702 rad_assert(openbraces == *open_p);
705 xlat_string = xlat_name;
708 } else if ((p[0] == ':') && (p[1] == '-')) { /* handle ':- */
709 DEBUG2("WARNING: Deprecated conditional expansion \":-\". See \"man unlang\" for details");
711 xlat_string = xlat_name;
714 } else { /* module name, followed by per-module string */
716 int delimitbrace = *open_p;
718 rad_assert(*p == ':');
719 p++; /* skip the ':' */
722 * If there's a brace immediately following the colon,
723 * then we've chosen to delimite the per-module string,
724 * so keep track of that.
727 delimitbrace = openbraces;
732 xlat_string = rad_malloc(strlen(p) + 1); /* always returns */
733 free_xlat_string = TRUE;
737 * Copy over the rest of the string, which is per-module
740 while (*p && !stop) {
744 * What the heck is this supposed
753 if (!spaces && p[1] == '-') {
762 * This is pretty hokey... we
763 * should use the functions in
773 if (openbraces == delimitbrace) {
795 * Now check to see if we're at the end of the string
796 * we were sent. If we're not, check for :-
798 if (openbraces == delimitbrace) {
799 if (p[0] == ':' && p[1] == '-') {
805 * Look up almost everything in the new tree of xlat
806 * functions. This makes it a little quicker...
809 if ((c = xlat_find(xlat_name)) != NULL) {
810 if (!c->internal) DEBUG3("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
811 c->module, xlat_string);
812 retlen = c->do_xlat(c->instance, request, xlat_string,
814 /* If retlen is 0, treat it as not found */
815 if (retlen > 0) found = 1;
820 * No attribute by that name, return an error.
822 DEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
828 * Skip to last '}' if attr is found
829 * The rest of the stuff within the braces is
830 * useless if we found what we need
834 snprintf(q, freespace, "%d", retlen);
840 while((*p != '\0') && (openbraces > *open_p)) {
842 * Handle escapes outside of the loop.
847 p++; /* get & ignore next character */
866 p++; /* skip the character */
871 if (free_xlat_string) free(xlat_string);
873 *open_p = openbraces;
879 * If the caller doesn't pass xlat an escape function, then
880 * we use this one. It simplifies the coding, as the check for
881 * func == NULL only happens once.
883 static int xlat_copy(char *out, int outlen, const char *in)
885 int freespace = outlen;
887 rad_assert(outlen > 0);
889 while ((*in) && (freespace > 1)) {
893 * FIXME: Do escaping of bad stuff!
901 return (outlen - freespace); /* count does not include NUL */
905 * Replace %<whatever> in a string.
907 * See 'doc/variables.txt' for more information.
909 int radius_xlat(char *out, int outlen, const char *fmt,
910 REQUEST *request, RADIUS_ESCAPE_STRING func)
912 int c, len, freespace;
918 char tmpdt[40]; /* For temporary storing of dates */
924 if (!fmt || !out || !request) return 0;
927 * Ensure that we always have an escaping function.
936 /* Calculate freespace in output */
937 freespace = outlen - (q - out);
942 if ((c != '%') && (c != '$') && (c != '\\')) {
944 * We check if we're inside an open brace. If we are
945 * then we assume this brace is NOT literal, but is
946 * a closing brace and apply it
948 if ((c == '}') && openbraces) {
958 * There's nothing after this character, copy
959 * the last '%' or "$' or '\\' over to the output
985 } else if (c == '%') switch(*p) {
987 decode_attribute(&p, &q, freespace, &openbraces, request, func);
993 case 'a': /* Protocol: */
994 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL),PW_TYPE_INTEGER, func);
997 case 'c': /* Callback-Number */
998 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER),PW_TYPE_STRING, func);
1001 case 'd': /* request day */
1002 TM = localtime_r(&request->timestamp, &s_TM);
1003 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
1005 strlcpy(q, tmpdt, freespace);
1010 case 'f': /* Framed IP address */
1011 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS),PW_TYPE_IPADDR, func);
1014 case 'i': /* Calling station ID */
1015 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID),PW_TYPE_STRING, func);
1018 case 'l': /* request timestamp */
1019 snprintf(tmpdt, sizeof(tmpdt), "%lu",
1020 (unsigned long) request->received.tv_sec);
1021 strlcpy(q,tmpdt,freespace);
1025 case 'm': /* request month */
1026 TM = localtime_r(&request->timestamp, &s_TM);
1027 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
1029 strlcpy(q, tmpdt, freespace);
1034 case 'n': /* NAS IP address */
1035 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS),PW_TYPE_IPADDR, func);
1038 case 'p': /* Port number */
1039 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT),PW_TYPE_INTEGER, func);
1042 case 's': /* Speed */
1043 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO),PW_TYPE_STRING, func);
1046 case 't': /* request timestamp */
1047 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
1048 nl = strchr(tmpdt, '\n');
1050 strlcpy(q, tmpdt, freespace);
1054 case 'u': /* User name */
1055 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME),PW_TYPE_STRING, func);
1058 case 'A': /* radacct_dir */
1059 strlcpy(q,radacct_dir,freespace);
1063 case 'C': /* ClientName */
1064 strlcpy(q,client_name_old(&request->packet->src_ipaddr),freespace);
1068 case 'D': /* request date */
1069 TM = localtime_r(&request->timestamp, &s_TM);
1070 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
1072 strlcpy(q, tmpdt, freespace);
1077 case 'H': /* request hour */
1078 TM = localtime_r(&request->timestamp, &s_TM);
1079 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
1081 strlcpy(q, tmpdt, freespace);
1086 case 'L': /* radlog_dir */
1087 strlcpy(q,radlog_dir,freespace);
1092 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU),PW_TYPE_INTEGER, func);
1095 case 'R': /* radius_dir */
1096 strlcpy(q,radius_dir,freespace);
1100 case 'S': /* request timestamp in SQL format*/
1101 TM = localtime_r(&request->timestamp, &s_TM);
1102 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1104 strlcpy(q, tmpdt, freespace);
1109 case 'T': /* request timestamp */
1110 TM = localtime_r(&request->timestamp, &s_TM);
1111 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1113 strlcpy(q, tmpdt, freespace);
1118 case 'U': /* Stripped User name */
1119 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME),PW_TYPE_STRING, func);
1122 case 'V': /* Request-Authenticator */
1123 strlcpy(q,"Verified",freespace);
1127 case 'Y': /* request year */
1128 TM = localtime_r(&request->timestamp, &s_TM);
1129 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1131 strlcpy(q, tmpdt, freespace);
1136 case 'Z': /* Full request pairs except password */
1137 tmp = request->packet->vps;
1138 while (tmp && (freespace > 3)) {
1139 if (tmp->attribute != PW_USER_PASSWORD) {
1141 len = vp_prints(q, freespace - 2, tmp);
1143 freespace -= (len + 2);
1151 DEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1152 if (freespace > 2) {
1161 DEBUG2("\texpand: %s -> %s", fmt, out);