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);
349 return 0; /* not found */
353 localvp.type = da->type;
354 return valuepair2str(out, outlen, &localvp,
364 if (!vps) return 0; /* silently fail */
367 * Convert the VP to a string, and return it.
369 return valuepair2str(out, outlen, vp, da->type, func);
374 * Pull %{0} to %{8} out of the packet.
376 static size_t xlat_regex(void *instance, REQUEST *request,
377 char *fmt, char *out, size_t outlen,
378 RADIUS_ESCAPE_STRING func)
383 * We cheat: fmt is "0" to "8", but those numbers
384 * are already in the "instance".
386 fmt = fmt; /* -Wunused */
387 func = func; /* -Wunused FIXME: do escaping? */
389 regex = request_data_reference(request, request,
390 REQUEST_DATA_REGEX | *(int *)instance);
391 if (!regex) return 0;
394 * Copy UP TO "freespace" bytes, including
397 strlcpy(out, regex, outlen);
400 #endif /* HAVE_REGEX_H */
404 * Compare two xlat_t structs, based ONLY on the module name.
406 static int xlat_cmp(const void *a, const void *b)
408 if (((const xlat_t *)a)->length != ((const xlat_t *)b)->length) {
409 return ((const xlat_t *)a)->length - ((const xlat_t *)b)->length;
412 return memcmp(((const xlat_t *)a)->module,
413 ((const xlat_t *)b)->module,
414 ((const xlat_t *)a)->length);
419 * find the appropriate registered xlat function.
421 static xlat_t *xlat_find(const char *module)
426 * Look for dictionary attributes first.
428 if ((dict_attrbyname(module) != NULL) ||
429 (strchr(module, '[') != NULL)) {
433 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
434 my_xlat.length = strlen(my_xlat.module);
436 return rbtree_finddata(xlat_root, &my_xlat);
441 * Register an xlat function.
443 int xlat_register(const char *module, RAD_XLAT_FUNC func, void *instance)
448 if ((module == NULL) || (strlen(module) == 0)) {
449 DEBUG("xlat_register: Invalid module name");
454 * First time around, build up the tree...
456 * FIXME: This code should be hoisted out of this function,
457 * and into a global "initialization". But it isn't critical...
465 xlat_root = rbtree_create(xlat_cmp, free, 0);
467 DEBUG("xlat_register: Failed to create tree.");
472 * Register the internal packet xlat's.
474 for (i = 0; internal_xlat[i] != NULL; i++) {
475 xlat_register(internal_xlat[i], xlat_packet, &xlat_inst[i]);
476 c = xlat_find(internal_xlat[i]);
477 rad_assert(c != NULL);
482 * New name: "control"
484 xlat_register("control", xlat_packet, &xlat_inst[0]);
485 c = xlat_find("control");
486 rad_assert(c != NULL);
491 * Register xlat's for regexes.
494 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
496 xlat_register(buffer, xlat_regex, &xlat_inst[i]);
497 c = xlat_find(buffer);
498 rad_assert(c != NULL);
501 #endif /* HAVE_REGEX_H */
505 * If it already exists, replace the instance.
507 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
508 my_xlat.length = strlen(my_xlat.module);
509 c = rbtree_finddata(xlat_root, &my_xlat);
512 DEBUG("xlat_register: Cannot re-define internal xlat");
517 c->instance = instance;
522 * Doesn't exist. Create it.
524 c = rad_malloc(sizeof(*c));
525 memset(c, 0, sizeof(*c));
528 strlcpy(c->module, module, sizeof(c->module));
529 c->length = strlen(c->module);
530 c->instance = instance;
532 rbtree_insert(xlat_root, c);
538 * Unregister an xlat function.
540 * We can only have one function to call per name, so the
541 * passing of "func" here is extraneous.
543 void xlat_unregister(const char *module, RAD_XLAT_FUNC func)
548 func = func; /* -Wunused */
552 strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
553 my_xlat.length = strlen(my_xlat.module);
555 node = rbtree_find(xlat_root, &my_xlat);
558 rbtree_delete(xlat_root, node);
562 * De-register all xlat functions,
563 * used mainly for debugging.
567 rbtree_free(xlat_root);
572 * Decode an attribute name into a string.
574 static void decode_attribute(const char **from, char **to, int freespace,
575 int *open_p, REQUEST *request,
576 RADIUS_ESCAPE_STRING func)
580 char *xlat_string = NULL; /* can be large */
581 int free_xlat_string = FALSE;
584 int found=0, retlen=0;
585 int openbraces = *open_p;
596 * Skip the '{' at the front of 'p'
597 * Increment open braces
608 * Handle %{%{foo}:-%{bar}}, which is useful, too.
610 * Did I mention that this parser is garbage?
612 if ((p[0] == '%') && (p[1] == '{')) {
614 * This is really bad, but it works.
617 size_t mylen = strlen(p);
618 char *first = rad_malloc(mylen);
619 char *second = rad_malloc(mylen);
622 len1 = rad_copy_variable(first, p);
624 DEBUG2("Badly formatted variable: %s", p);
628 if ((p[len1] != ':') || (p[len1 + 1] != '-')) {
629 DEBUG2("No trailing :- after variable at %s", p);
635 if ((p[0] == '%') && (p[1] == '{')) {
636 len2 = rad_copy_variable(second, p);
640 DEBUG2("Invalid text after :- at %s", p);
645 } else if ((p[0] == '"') || p[0] == '\'') {
646 getstring(&p, second, mylen);
651 while (*p && (*p != '}')) {
658 DEBUG2("Failed to find trailing '}' in string");
662 mylen = radius_xlat(q, freespace, first, request, func);
669 strlcpy(q, second, freespace);
672 mylen = radius_xlat(q, freespace, second,
681 * Else the output is an empty string.
691 * First, copy the xlat key name to one buffer
693 while (*p && (*p != '}') && (*p != ':')) {
696 if (pa >= (xlat_name + sizeof(xlat_name) - 1)) {
698 * Skip to the end of the input
701 DEBUG("xlat: Module name is too long in string %%%s",
709 DEBUG("xlat: Invalid syntax in %s", *from);
712 * %{name} is a simple attribute reference,
713 * or regex reference.
715 } else if (*p == '}') {
717 rad_assert(openbraces == *open_p);
720 xlat_string = xlat_name;
723 } else if ((p[0] == ':') && (p[1] == '-')) { /* handle ':- */
724 DEBUG2("WARNING: Deprecated conditional expansion \":-\". See \"man unlang\" for details");
726 xlat_string = xlat_name;
729 } else { /* module name, followed by per-module string */
731 int delimitbrace = *open_p;
733 rad_assert(*p == ':');
734 p++; /* skip the ':' */
737 * If there's a brace immediately following the colon,
738 * then we've chosen to delimite the per-module string,
739 * so keep track of that.
742 delimitbrace = openbraces;
747 xlat_string = rad_malloc(strlen(p) + 1); /* always returns */
748 free_xlat_string = TRUE;
752 * Copy over the rest of the string, which is per-module
755 while (*p && !stop) {
759 * What the heck is this supposed
768 if (!spaces && p[1] == '-') {
777 * This is pretty hokey... we
778 * should use the functions in
788 if (openbraces == delimitbrace) {
810 * Now check to see if we're at the end of the string
811 * we were sent. If we're not, check for :-
813 if (openbraces == delimitbrace) {
814 if (p[0] == ':' && p[1] == '-') {
820 * Look up almost everything in the new tree of xlat
821 * functions. This makes it a little quicker...
824 if ((c = xlat_find(xlat_name)) != NULL) {
825 if (!c->internal) DEBUG3("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
826 c->module, xlat_string);
827 retlen = c->do_xlat(c->instance, request, xlat_string,
829 /* If retlen is 0, treat it as not found */
830 if (retlen > 0) found = 1;
835 * No attribute by that name, return an error.
837 DEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
843 * Skip to last '}' if attr is found
844 * The rest of the stuff within the braces is
845 * useless if we found what we need
849 snprintf(q, freespace, "%d", retlen);
855 while((*p != '\0') && (openbraces > *open_p)) {
857 * Handle escapes outside of the loop.
862 p++; /* get & ignore next character */
881 p++; /* skip the character */
886 if (free_xlat_string) free(xlat_string);
888 *open_p = openbraces;
894 * If the caller doesn't pass xlat an escape function, then
895 * we use this one. It simplifies the coding, as the check for
896 * func == NULL only happens once.
898 static size_t xlat_copy(char *out, size_t outlen, const char *in)
900 int freespace = outlen;
902 rad_assert(outlen > 0);
904 while ((*in) && (freespace > 1)) {
908 * FIXME: Do escaping of bad stuff!
916 return (outlen - freespace); /* count does not include NUL */
920 * Replace %<whatever> in a string.
922 * See 'doc/variables.txt' for more information.
924 int radius_xlat(char *out, int outlen, const char *fmt,
925 REQUEST *request, RADIUS_ESCAPE_STRING func)
927 int c, len, freespace;
933 char tmpdt[40]; /* For temporary storing of dates */
939 if (!fmt || !out || !request) return 0;
942 * Ensure that we always have an escaping function.
951 /* Calculate freespace in output */
952 freespace = outlen - (q - out);
957 if ((c != '%') && (c != '$') && (c != '\\')) {
959 * We check if we're inside an open brace. If we are
960 * then we assume this brace is NOT literal, but is
961 * a closing brace and apply it
963 if ((c == '}') && openbraces) {
973 * There's nothing after this character, copy
974 * the last '%' or "$' or '\\' over to the output
1000 } else if (c == '%') switch(*p) {
1002 decode_attribute(&p, &q, freespace, &openbraces, request, func);
1008 case 'a': /* Protocol: */
1009 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL),PW_TYPE_INTEGER, func);
1012 case 'c': /* Callback-Number */
1013 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER),PW_TYPE_STRING, func);
1016 case 'd': /* request day */
1017 TM = localtime_r(&request->timestamp, &s_TM);
1018 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
1020 strlcpy(q, tmpdt, freespace);
1025 case 'f': /* Framed IP address */
1026 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS),PW_TYPE_IPADDR, func);
1029 case 'i': /* Calling station ID */
1030 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID),PW_TYPE_STRING, func);
1033 case 'l': /* request timestamp */
1034 snprintf(tmpdt, sizeof(tmpdt), "%lu",
1035 (unsigned long) request->received.tv_sec);
1036 strlcpy(q,tmpdt,freespace);
1040 case 'm': /* request month */
1041 TM = localtime_r(&request->timestamp, &s_TM);
1042 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
1044 strlcpy(q, tmpdt, freespace);
1049 case 'n': /* NAS IP address */
1050 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS),PW_TYPE_IPADDR, func);
1053 case 'p': /* Port number */
1054 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT),PW_TYPE_INTEGER, func);
1057 case 's': /* Speed */
1058 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO),PW_TYPE_STRING, func);
1061 case 't': /* request timestamp */
1062 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
1063 nl = strchr(tmpdt, '\n');
1065 strlcpy(q, tmpdt, freespace);
1069 case 'u': /* User name */
1070 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME),PW_TYPE_STRING, func);
1073 case 'A': /* radacct_dir */
1074 strlcpy(q,radacct_dir,freespace);
1078 case 'C': /* ClientName */
1079 strlcpy(q,request->client->shortname,freespace);
1083 case 'D': /* request date */
1084 TM = localtime_r(&request->timestamp, &s_TM);
1085 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
1087 strlcpy(q, tmpdt, freespace);
1092 case 'H': /* request hour */
1093 TM = localtime_r(&request->timestamp, &s_TM);
1094 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
1096 strlcpy(q, tmpdt, freespace);
1101 case 'L': /* radlog_dir */
1102 strlcpy(q,radlog_dir,freespace);
1107 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU),PW_TYPE_INTEGER, func);
1110 case 'R': /* radius_dir */
1111 strlcpy(q,radius_dir,freespace);
1115 case 'S': /* request timestamp in SQL format*/
1116 TM = localtime_r(&request->timestamp, &s_TM);
1117 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1119 strlcpy(q, tmpdt, freespace);
1124 case 'T': /* request timestamp */
1125 TM = localtime_r(&request->timestamp, &s_TM);
1126 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1128 strlcpy(q, tmpdt, freespace);
1133 case 'U': /* Stripped User name */
1134 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME),PW_TYPE_STRING, func);
1137 case 'V': /* Request-Authenticator */
1138 strlcpy(q,"Verified",freespace);
1142 case 'Y': /* request year */
1143 TM = localtime_r(&request->timestamp, &s_TM);
1144 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1146 strlcpy(q, tmpdt, freespace);
1151 case 'Z': /* Full request pairs except password */
1152 tmp = request->packet->vps;
1153 while (tmp && (freespace > 3)) {
1154 if (tmp->attribute != PW_USER_PASSWORD) {
1156 len = vp_prints(q, freespace - 2, tmp);
1158 freespace -= (len + 2);
1166 DEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1167 if (freespace > 2) {
1176 DEBUG2("\texpand: %s -> %s", fmt, out);