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/autoconf.h>
35 #include <freeradius-devel/radiusd.h>
37 #include <freeradius-devel/rad_assert.h>
39 typedef struct xlat_t {
40 char module[MAX_STRING_LEN];
43 RAD_XLAT_FUNC do_xlat;
44 int internal; /* not allowed to re-define these */
47 static rbtree_t *xlat_root = NULL;
50 * Define all xlat's in the structure.
52 static const char * const internal_xlat[] = {"check",
59 #if REQUEST_MAX_REGEX > 8
60 #error Please fix the following line
62 static const int xlat_inst[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; /* up to 8 for regex */
66 * Convert the value on a VALUE_PAIR to string
68 static int valuepair2str(char * out,int outlen,VALUE_PAIR * pair,
69 int type, RADIUS_ESCAPE_STRING func)
71 char buffer[MAX_STRING_LEN * 4];
74 vp_prints_value(buffer, sizeof(buffer), pair, -1);
75 return func(out, outlen, buffer);
80 strlcpy(out,"_",outlen);
82 case PW_TYPE_INTEGER :
83 strlcpy(out,"0",outlen);
86 strlcpy(out,"?.?.?.?",outlen);
88 case PW_TYPE_IPV6ADDR :
89 strlcpy(out,":?:",outlen);
92 strlcpy(out,"0",outlen);
95 strlcpy(out,"unknown_type",outlen);
102 * Dynamically translate for check:, request:, reply:, etc.
104 static int xlat_packet(void *instance, REQUEST *request,
105 char *fmt, char *out, size_t outlen,
106 RADIUS_ESCAPE_STRING func)
110 VALUE_PAIR *vps = NULL;
111 RADIUS_PACKET *packet = NULL;
113 switch (*(int*) instance) {
115 vps = request->config_items;
119 vps = request->packet->vps;
120 packet = request->packet;
124 vps = request->reply->vps;
125 packet = request->reply;
129 if (request->proxy) vps = request->proxy->vps;
130 packet = request->proxy;
134 if (request->proxy_reply) vps = request->proxy_reply->vps;
135 packet = request->proxy_reply;
143 * The "format" string is the attribute name.
145 da = dict_attrbyname(fmt);
148 const char *p = strchr(fmt, '[');
152 if (strlen(fmt) > sizeof(buffer)) return 0;
154 strlcpy(buffer, fmt, p - fmt + 1);
156 da = dict_attrbyname(buffer);
160 * %{Attribute-Name[#]} returns the count of
161 * attributes of that name in the list.
163 if ((p[1] == '#') && (p[2] == ']')) {
166 for (vp = pairfind(vps, da->attr);
168 vp = pairfind(vp->next, da->attr)) {
171 snprintf(out, outlen, "%d", count);
176 * %{Attribute-Name[*]} returns ALL of the
177 * the attributes, separated by a newline.
179 if ((p[1] == '*') && (p[2] == ']')) {
182 for (vp = pairfind(vps, da->attr);
184 vp = pairfind(vp->next, da->attr)) {
185 count = valuepair2str(out, outlen - 1, vp, da->type, func);
186 rad_assert(count <= outlen);
188 outlen -= (count + 1);
193 if (outlen == 0) break;
204 p += 1 + strspn(p + 1, "0123456789");
206 DEBUG2("xlat: Invalid array reference in string at %s %s",
212 * Find the N'th value.
214 for (vp = pairfind(vps, da->attr);
216 vp = pairfind(vp->next, da->attr)) {
217 if (count == 0) break;
222 * Non-existent array reference.
226 return valuepair2str(out, outlen, vp, da->type, func);
229 vp = pairfind(vps, da->attr);
232 * Some "magic" handlers, which are never in VP's, but
233 * which are in the packet.
235 * FIXME: We should really do this in a more
241 localvp.vp_strvalue[0] = 0;
248 dval = dict_valbyattr(da->attr, packet->code);
250 snprintf(out, outlen, "%s", dval->name);
252 snprintf(out, outlen, "%d", packet->code);
258 case PW_CLIENT_IP_ADDRESS: /* the same as below */
259 case PW_PACKET_SRC_IP_ADDRESS:
260 if (packet->src_ipaddr.af != AF_INET) {
263 localvp.attribute = da->attr;
264 localvp.lvalue = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
267 case PW_PACKET_DST_IP_ADDRESS:
268 if (packet->dst_ipaddr.af != AF_INET) {
271 localvp.attribute = da->attr;
272 localvp.lvalue = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
275 case PW_PACKET_SRC_PORT:
276 localvp.attribute = da->attr;
277 localvp.lvalue = packet->src_port;
280 case PW_PACKET_DST_PORT:
281 localvp.attribute = da->attr;
282 localvp.lvalue = packet->dst_port;
285 case PW_PACKET_AUTHENTICATION_VECTOR:
286 localvp.attribute = da->attr;
287 memcpy(localvp.vp_strvalue, packet->vector,
288 sizeof(packet->vector));
289 localvp.length = sizeof(packet->vector);
293 * Authorization, accounting, etc.
295 case PW_REQUEST_PROCESSING_STAGE:
296 if (request->component) {
297 strlcpy(out, request->component, outlen);
299 strlcpy(out, "server_core", outlen);
303 case PW_PACKET_SRC_IPV6_ADDRESS:
304 if (packet->src_ipaddr.af != AF_INET6) {
307 localvp.attribute = da->attr;
308 memcpy(localvp.vp_strvalue,
309 &packet->src_ipaddr.ipaddr.ip6addr,
310 sizeof(packet->src_ipaddr.ipaddr.ip6addr));
313 case PW_PACKET_DST_IPV6_ADDRESS:
314 if (packet->dst_ipaddr.af != AF_INET6) {
317 localvp.attribute = da->attr;
318 memcpy(localvp.vp_strvalue,
319 &packet->dst_ipaddr.ipaddr.ip6addr,
320 sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
323 case PW_SERVER_IDENTITY:
324 if (!request->listener || !request->listener->identity) return 0;
326 snprintf(out, outlen, "%s", request->listener->identity);
331 return 0; /* not found */
335 localvp.type = da->type;
336 return valuepair2str(out, outlen, &localvp,
346 if (!vps) return 0; /* silently fail */
349 * Convert the VP to a string, and return it.
351 return valuepair2str(out, outlen, vp, da->type, func);
356 * Pull %{0} to %{8} out of the packet.
358 static int xlat_regex(void *instance, REQUEST *request,
359 char *fmt, char *out, size_t outlen,
360 RADIUS_ESCAPE_STRING func)
365 * We cheat: fmt is "0" to "8", but those numbers
366 * are already in the "instance".
368 fmt = fmt; /* -Wunused */
369 func = func; /* -Wunused FIXME: do escaping? */
371 regex = request_data_reference(request, request,
372 REQUEST_DATA_REGEX | *(int *)instance);
373 if (!regex) return 0;
376 * Copy UP TO "freespace" bytes, including
379 strlcpy(out, regex, outlen);
382 #endif /* HAVE_REGEX_H */
385 * Compare two xlat_t structs, based ONLY on the module name.
387 static int xlat_cmp(const void *a, const void *b)
389 if (((const xlat_t *)a)->length != ((const xlat_t *)b)->length) {
390 return ((const xlat_t *)a)->length - ((const xlat_t *)b)->length;
393 return memcmp(((const xlat_t *)a)->module,
394 ((const xlat_t *)b)->module,
395 ((const xlat_t *)a)->length);
400 * find the appropriate registered xlat function.
402 static const xlat_t *xlat_find(const char *module)
407 * Look for dictionary attributes first.
409 if ((dict_attrbyname(module) != NULL) ||
410 (strchr(module, '[') != NULL)) {
411 static const xlat_t dict_xlat = {
422 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
423 my_xlat.length = strlen(my_xlat.module);
425 return rbtree_finddata(xlat_root, &my_xlat);
430 * Register an xlat function.
432 int xlat_register(const char *module, RAD_XLAT_FUNC func, void *instance)
437 if ((module == NULL) || (strlen(module) == 0)) {
438 DEBUG("xlat_register: Invalid module name");
443 * First time around, build up the tree...
445 * FIXME: This code should be hoisted out of this function,
446 * and into a global "initialization". But it isn't critical...
454 xlat_root = rbtree_create(xlat_cmp, free, 0);
456 DEBUG("xlat_register: Failed to create tree.");
461 * Register the internal packet xlat's.
463 for (i = 0; internal_xlat[i] != NULL; i++) {
464 xlat_register(internal_xlat[i], xlat_packet, &xlat_inst[i]);
465 c = xlat_find(internal_xlat[i]);
466 rad_assert(c != NULL);
472 * Register xlat's for regexes.
475 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
477 xlat_register(buffer, xlat_regex, &xlat_inst[i]);
478 c = xlat_find(buffer);
479 rad_assert(c != NULL);
482 #endif /* HAVE_REGEX_H */
486 * If it already exists, replace the instance.
488 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
489 my_xlat.length = strlen(my_xlat.module);
490 c = rbtree_finddata(xlat_root, &my_xlat);
493 DEBUG("xlat_register: Cannot re-define internal xlat");
498 c->instance = instance;
503 * Doesn't exist. Create it.
505 c = rad_malloc(sizeof(xlat_t));
506 memset(c, 0, sizeof(*c));
509 strlcpy(c->module, module, sizeof(c->module));
510 c->length = strlen(c->module);
511 c->instance = instance;
513 rbtree_insert(xlat_root, c);
519 * Unregister an xlat function.
521 * We can only have one function to call per name, so the
522 * passing of "func" here is extraneous.
524 void xlat_unregister(const char *module, RAD_XLAT_FUNC func)
529 func = func; /* -Wunused */
533 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
534 my_xlat.length = strlen(my_xlat.module);
536 node = rbtree_find(xlat_root, &my_xlat);
539 rbtree_delete(xlat_root, node);
543 * De-register all xlat functions,
544 * used mainly for debugging.
548 rbtree_free(xlat_root);
553 * Decode an attribute name into a string.
555 static void decode_attribute(const char **from, char **to, int freespace,
556 int *open, REQUEST *request,
557 RADIUS_ESCAPE_STRING func)
561 char *xlat_string = NULL; /* can be large */
562 int free_xlat_string = FALSE;
565 int found=0, retlen=0;
566 int openbraces = *open;
576 * Skip the '{' at the front of 'p'
577 * Increment open braces
588 * First, copy the xlat key name to one buffer
590 while (*p && (*p != '}') && (*p != ':')) {
593 if (pa >= (xlat_name + sizeof(xlat_name) - 1)) {
595 * Skip to the end of the input
598 DEBUG("xlat: Module name is too long in string %%%s",
606 DEBUG("xlat: Invalid syntax in %s", *from);
609 * %{name} is a simple attribute reference,
610 * or regex reference.
612 } else if (*p == '}') {
614 rad_assert(openbraces == *open);
617 xlat_string = xlat_name;
620 } else if (p[1] == '-') { /* handle ':- */
622 xlat_string = xlat_name;
625 } else { /* module name, followed by per-module string */
627 int delimitbrace = *open;
629 rad_assert(*p == ':');
630 p++; /* skip the ':' */
633 * If there's a brace immediately following the colon,
634 * then we've chosen to delimite the per-module string,
635 * so keep track of that.
638 delimitbrace = openbraces;
643 xlat_string = rad_malloc(strlen(p) + 1); /* always returns */
644 free_xlat_string = TRUE;
648 * Copy over the rest of the string, which is per-module
651 while (*p && !stop) {
654 * What the heck is this supposed
663 * This is pretty hokey... we
664 * should use the functions in
674 if (openbraces == delimitbrace) {
691 * Now check to see if we're at the end of the string
692 * we were sent. If we're not, check for :-
694 if (openbraces == delimitbrace) {
695 if (p[0] == ':' && p[1] == '-') {
701 * Look up almost everything in the new tree of xlat
702 * functions. This makes it a little quicker...
705 if ((c = xlat_find(xlat_name)) != NULL) {
706 if (!c->internal) DEBUG("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
707 c->module, xlat_string);
708 retlen = c->do_xlat(c->instance, request, xlat_string,
710 /* If retlen is 0, treat it as not found */
711 if (retlen > 0) found = 1;
715 * No attribute by that name, return an error.
717 DEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
723 * Skip to last '}' if attr is found
724 * The rest of the stuff within the braces is
725 * useless if we found what we need
729 snprintf(q, freespace, "%d", retlen);
735 while((*p != '\0') && (openbraces > *open)) {
737 * Handle escapes outside of the loop.
742 p++; /* get & ignore next character */
761 p++; /* skip the character */
766 if (free_xlat_string) free(xlat_string);
774 * If the caller doesn't pass xlat an escape function, then
775 * we use this one. It simplifies the coding, as the check for
776 * func == NULL only happens once.
778 static int xlat_copy(char *out, int outlen, const char *in)
780 int freespace = outlen;
782 rad_assert(outlen > 0);
784 while ((*in) && (freespace > 1)) {
788 * FIXME: Do escaping of bad stuff!
796 return (outlen - freespace); /* count does not include NUL */
800 * Replace %<whatever> in a string.
802 * See 'doc/variables.txt' for more information.
804 int radius_xlat(char *out, int outlen, const char *fmt,
805 REQUEST *request, RADIUS_ESCAPE_STRING func)
807 int c, len, freespace;
813 char tmpdt[40]; /* For temporary storing of dates */
819 if (!fmt || !out || !request) return 0;
822 * Ensure that we always have an escaping function.
831 /* Calculate freespace in output */
832 freespace = outlen - (q - out);
837 if ((c != '%') && (c != '$') && (c != '\\')) {
839 * We check if we're inside an open brace. If we are
840 * then we assume this brace is NOT literal, but is
841 * a closing brace and apply it
843 if ((c == '}') && openbraces) {
853 * There's nothing after this character, copy
854 * the last '%' or "$' or '\\' over to the output
881 * Hmmm... ${User-Name} is a synonym for
886 } else if (c == '$') switch(*p) {
887 case '{': /* Attribute by Name */
888 decode_attribute(&p, &q, freespace, &openbraces, request, func);
895 } else if (c == '%') switch(*p) {
897 decode_attribute(&p, &q, freespace, &openbraces, request, func);
903 case 'a': /* Protocol: */
904 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL),PW_TYPE_INTEGER, func);
907 case 'c': /* Callback-Number */
908 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER),PW_TYPE_STRING, func);
911 case 'd': /* request day */
912 TM = localtime_r(&request->timestamp, &s_TM);
913 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
915 strlcpy(q, tmpdt, freespace);
920 case 'f': /* Framed IP address */
921 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS),PW_TYPE_IPADDR, func);
924 case 'i': /* Calling station ID */
925 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID),PW_TYPE_STRING, func);
928 case 'l': /* request timestamp */
929 snprintf(tmpdt, sizeof(tmpdt), "%lu",
930 (unsigned long) request->timestamp);
931 strlcpy(q,tmpdt,freespace);
935 case 'm': /* request month */
936 TM = localtime_r(&request->timestamp, &s_TM);
937 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
939 strlcpy(q, tmpdt, freespace);
944 case 'n': /* NAS IP address */
945 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS),PW_TYPE_IPADDR, func);
948 case 'p': /* Port number */
949 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT),PW_TYPE_INTEGER, func);
952 case 's': /* Speed */
953 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO),PW_TYPE_STRING, func);
956 case 't': /* request timestamp */
957 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
958 nl = strchr(tmpdt, '\n');
960 strlcpy(q, tmpdt, freespace);
964 case 'u': /* User name */
965 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME),PW_TYPE_STRING, func);
968 case 'A': /* radacct_dir */
969 strlcpy(q,radacct_dir,freespace);
973 case 'C': /* ClientName */
974 strlcpy(q,client_name_old(&request->packet->src_ipaddr),freespace);
978 case 'D': /* request date */
979 TM = localtime_r(&request->timestamp, &s_TM);
980 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
982 strlcpy(q, tmpdt, freespace);
987 case 'H': /* request hour */
988 TM = localtime_r(&request->timestamp, &s_TM);
989 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
991 strlcpy(q, tmpdt, freespace);
996 case 'L': /* radlog_dir */
997 strlcpy(q,radlog_dir,freespace);
1002 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU),PW_TYPE_INTEGER, func);
1005 case 'R': /* radius_dir */
1006 strlcpy(q,radius_dir,freespace);
1010 case 'S': /* request timestamp in SQL format*/
1011 TM = localtime_r(&request->timestamp, &s_TM);
1012 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1014 strlcpy(q, tmpdt, freespace);
1019 case 'T': /* request timestamp */
1020 TM = localtime_r(&request->timestamp, &s_TM);
1021 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1023 strlcpy(q, tmpdt, freespace);
1028 case 'U': /* Stripped User name */
1029 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME),PW_TYPE_STRING, func);
1032 case 'V': /* Request-Authenticator */
1033 if (request->packet->verified)
1034 strlcpy(q,"Verified",freespace);
1036 strlcpy(q,"None",freespace);
1040 case 'Y': /* request year */
1041 TM = localtime_r(&request->timestamp, &s_TM);
1042 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1044 strlcpy(q, tmpdt, freespace);
1049 case 'Z': /* Full request pairs except password */
1050 tmp = request->packet->vps;
1051 while (tmp && (freespace > 3)) {
1052 if (tmp->attribute != PW_USER_PASSWORD) {
1054 len = vp_prints(q, freespace - 2, tmp);
1056 freespace -= (len + 2);
1064 DEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1065 if (freespace > 2) {
1074 DEBUG2("radius_xlat: '%s'", out);