6bbf474c7d8141a7d41a240543c38de363bb0ef9
[freeradius.git] / src / main / xlat.c
1 /*
2  * xlat.c       Translate strings.  This is the first version of xlat
3  *              incorporated to RADIUS
4  *
5  * Version:     $Id$
6  *
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.
11  *
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.
16  *
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
20  *
21  * Copyright 2000,2006  The FreeRADIUS server project
22  * Copyright 2000  Alan DeKok <aland@ox.org>
23  */
24
25 #include <freeradius-devel/ident.h>
26 RCSID("$Id$")
27
28 #include        <freeradius-devel/radiusd.h>
29 #include        <freeradius-devel/md5.h>
30 #include        <freeradius-devel/rad_assert.h>
31
32 #include        <ctype.h>
33
34 typedef struct xlat_t {
35         char            module[MAX_STRING_LEN];
36         int             length;
37         void            *instance;
38         RAD_XLAT_FUNC   do_xlat;
39         int             internal;       /* not allowed to re-define these */
40 } xlat_t;
41
42 static rbtree_t *xlat_root = NULL;
43
44 /*
45  *      Define all xlat's in the structure.
46  */
47 static const char * const internal_xlat[] = {"check",
48                                              "request",
49                                              "reply",
50                                              "proxy-request",
51                                              "proxy-reply",
52                                              "outer.request",
53                                              "outer.reply",
54                                              NULL};
55
56 #if REQUEST_MAX_REGEX > 8
57 #error Please fix the following line
58 #endif
59 static const int xlat_inst[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };   /* up to 8 for regex */
60
61
62 /*
63  *      Convert the value on a VALUE_PAIR to string
64  */
65 static int valuepair2str(char * out,int outlen,VALUE_PAIR * pair,
66                          int type, RADIUS_ESCAPE_STRING func)
67 {
68         char buffer[MAX_STRING_LEN * 4];
69
70         if (pair != NULL) {
71                 vp_prints_value(buffer, sizeof(buffer), pair, -1);
72                 return func(out, outlen, buffer);
73         }
74
75         switch (type) {
76         case PW_TYPE_STRING :
77                 strlcpy(out,"_",outlen);
78                 break;
79         case PW_TYPE_INTEGER :
80                 strlcpy(out,"0",outlen);
81                 break;
82         case PW_TYPE_IPADDR :
83                 strlcpy(out,"?.?.?.?",outlen);
84                 break;
85         case PW_TYPE_IPV6ADDR :
86                 strlcpy(out,":?:",outlen);
87                 break;
88         case PW_TYPE_DATE :
89                 strlcpy(out,"0",outlen);
90                 break;
91         default :
92                 strlcpy(out,"unknown_type",outlen);
93         }
94         return strlen(out);
95 }
96
97
98 /*
99  *      Dynamically translate for check:, request:, reply:, etc.
100  */
101 static size_t xlat_packet(void *instance, REQUEST *request,
102                           char *fmt, char *out, size_t outlen,
103                           RADIUS_ESCAPE_STRING func)
104 {
105         DICT_ATTR       *da;
106         VALUE_PAIR      *vp;
107         VALUE_PAIR      *vps = NULL;
108         RADIUS_PACKET   *packet = NULL;
109
110         switch (*(int*) instance) {
111         case 0:
112                 vps = request->config_items;
113                 break;
114
115         case 1:
116                 vps = request->packet->vps;
117                 packet = request->packet;
118                 break;
119
120         case 2:
121                 vps = request->reply->vps;
122                 packet = request->reply;
123                 break;
124
125         case 3:
126 #ifdef WITH_PROXY
127                 if (request->proxy) vps = request->proxy->vps;
128                 packet = request->proxy;
129 #endif
130                 break;
131
132         case 4:
133 #ifdef WITH_PROXY
134                 if (request->proxy_reply) vps = request->proxy_reply->vps;
135                 packet = request->proxy_reply;
136 #endif
137                 break;
138
139         case 5:
140                 if (request->parent) {
141                         vps = request->parent->packet->vps;
142                         packet = request->parent->packet;
143                 }
144                 break;
145                         
146         case 6:
147                 if (request->parent && request->parent->reply) {
148                         vps = request->parent->reply->vps;
149                         packet = request->parent->reply;
150                 }
151                 break;
152                         
153         default:                /* WTF? */
154                 return 0;
155         }
156
157         /*
158          *      The "format" string is the attribute name.
159          */
160         da = dict_attrbyname(fmt);
161         if (!da) {
162                 int do_number = FALSE;
163                 size_t count;
164                 const char *p;
165                 char buffer[256];
166
167                 if (strlen(fmt) > sizeof(buffer)) return 0;
168
169                 p = strchr(fmt, '[');
170                 if (!p) {
171                         p = strchr(fmt, '#');
172                         if (!p) return 0;
173                         do_number = TRUE;
174                 }
175
176                 strlcpy(buffer, fmt, p - fmt + 1);
177
178                 da = dict_attrbyname(buffer);
179                 if (!da) return 0;
180
181                 if (do_number) {
182                         vp = pairfind(vps, da->attr, 0);
183                         if (!vp) return 0;
184
185                         switch (da->type) {
186                         default:
187                                 break;
188
189                         case PW_TYPE_INTEGER:
190                         case PW_TYPE_DATE:
191                         case PW_TYPE_SHORT:
192                         case PW_TYPE_BYTE:
193                                 snprintf(out, outlen, "%u", vp->lvalue);
194                                 return strlen(out);
195                         }
196
197                         goto just_print;
198                 }
199
200                 /*
201                  *      %{Attribute-Name[#]} returns the count of
202                  *      attributes of that name in the list.
203                  */
204                 if ((p[1] == '#') && (p[2] == ']')) {
205                         count = 0;
206
207                         for (vp = pairfind(vps, da->attr, da->vendor);
208                              vp != NULL;
209                              vp = pairfind(vp->next, da->attr, da->vendor)) {
210                                 count++;
211                         }
212                         snprintf(out, outlen, "%d", (int) count);
213                         return strlen(out);
214                 }
215
216                 /*
217                  *      %{Attribute-Name[*]} returns ALL of the
218                  *      the attributes, separated by a newline.
219                  */
220                 if ((p[1] == '*') && (p[2] == ']')) {
221                         int total = 0;
222
223                         for (vp = pairfind(vps, da->attr, da->vendor);
224                              vp != NULL;
225                              vp = pairfind(vp->next, da->attr, da->vendor)) {
226                                 count = valuepair2str(out, outlen - 1, vp, da->type, func);
227                                 rad_assert(count <= outlen);
228                                 total += count + 1;
229                                 outlen -= (count + 1);
230                                 out += count;
231
232                                 *(out++) = '\n';
233
234                                 if (outlen == 0) break;
235                         }
236
237                         return total;
238                 }
239
240                 count = atoi(p + 1);
241
242                 /*
243                  *      Skip the numbers.
244                  */
245                 p += 1 + strspn(p + 1, "0123456789");
246                 if (*p != ']') {
247                         RDEBUG2("xlat: Invalid array reference in string at %s %s",
248                                fmt, p);
249                         return 0;
250                 }
251
252                 /*
253                  *      Find the N'th value.
254                  */
255                 for (vp = pairfind(vps, da->attr, da->vendor);
256                      vp != NULL;
257                      vp = pairfind(vp->next, da->attr, da->vendor)) {
258                         if (count == 0) break;
259                         count--;
260                 }
261
262                 /*
263                  *      Non-existent array reference.
264                  */
265                 if (!vp) return 0;
266         just_print:
267                 return valuepair2str(out, outlen, vp, da->type, func);
268         }
269
270         vp = pairfind(vps, da->attr, da->vendor);
271         if (!vp) {
272                 /*
273                  *      Some "magic" handlers, which are never in VP's, but
274                  *      which are in the packet.
275                  *
276                  *      FIXME: We should really do this in a more
277                  *      intelligent way...
278                  */
279                 if (packet) {
280                         VALUE_PAIR localvp;
281
282                         memset(&localvp, 0, sizeof(localvp));
283
284                         switch (da->attr) {
285                         case PW_PACKET_TYPE:
286                         {
287                                 DICT_VALUE *dval;
288
289                                 dval = dict_valbyattr(da->attr, da->vendor, packet->code);
290                                 if (dval) {
291                                         snprintf(out, outlen, "%s", dval->name);
292                                 } else {
293                                         snprintf(out, outlen, "%d", packet->code);
294                                 }
295                                 return strlen(out);
296                         }
297                         break;
298
299                         case PW_CLIENT_SHORTNAME:
300                                 if (request->client && request->client->shortname) {
301                                         strlcpy(out, request->client->shortname, outlen);
302                                 } else {
303                                         strlcpy(out, "<UNKNOWN-CLIENT>", outlen);
304                                 }
305                                 return strlen(out);
306
307                         case PW_CLIENT_IP_ADDRESS: /* the same as below */
308                         case PW_PACKET_SRC_IP_ADDRESS:
309                                 if (packet->src_ipaddr.af != AF_INET) {
310                                         return 0;
311                                 }
312                                 localvp.attribute = da->attr;
313                                 localvp.vp_ipaddr = packet->src_ipaddr.ipaddr.ip4addr.s_addr;
314                                 break;
315
316                         case PW_PACKET_DST_IP_ADDRESS:
317                                 if (packet->dst_ipaddr.af != AF_INET) {
318                                         return 0;
319                                 }
320                                 localvp.attribute = da->attr;
321                                 localvp.vp_ipaddr = packet->dst_ipaddr.ipaddr.ip4addr.s_addr;
322                                 break;
323
324                         case PW_PACKET_SRC_PORT:
325                                 localvp.attribute = da->attr;
326                                 localvp.vp_integer = packet->src_port;
327                                 break;
328
329                         case PW_PACKET_DST_PORT:
330                                 localvp.attribute = da->attr;
331                                 localvp.vp_integer = packet->dst_port;
332                                 break;
333
334                         case PW_PACKET_AUTHENTICATION_VECTOR:
335                                 localvp.attribute = da->attr;
336                                 memcpy(localvp.vp_strvalue, packet->vector,
337                                        sizeof(packet->vector));
338                                 localvp.length = sizeof(packet->vector);
339                                 break;
340
341                                 /*
342                                  *      Authorization, accounting, etc.
343                                  */
344                         case PW_REQUEST_PROCESSING_STAGE:
345                                 if (request->component) {
346                                         strlcpy(out, request->component, outlen);
347                                 } else {
348                                         strlcpy(out, "server_core", outlen);
349                                 }
350                                 return strlen(out);
351
352                         case PW_PACKET_SRC_IPV6_ADDRESS:
353                                 if (packet->src_ipaddr.af != AF_INET6) {
354                                         return 0;
355                                 }
356                                 localvp.attribute = da->attr;
357                                 memcpy(localvp.vp_strvalue,
358                                        &packet->src_ipaddr.ipaddr.ip6addr,
359                                        sizeof(packet->src_ipaddr.ipaddr.ip6addr));
360                                 break;
361
362                         case PW_PACKET_DST_IPV6_ADDRESS:
363                                 if (packet->dst_ipaddr.af != AF_INET6) {
364                                         return 0;
365                                 }
366                                 localvp.attribute = da->attr;
367                                 memcpy(localvp.vp_strvalue,
368                                        &packet->dst_ipaddr.ipaddr.ip6addr,
369                                        sizeof(packet->dst_ipaddr.ipaddr.ip6addr));
370                                 break;
371
372                         case PW_VIRTUAL_SERVER:
373                                 if (!request->server) return 0;
374
375                                 snprintf(out, outlen, "%s", request->server);
376                                 return strlen(out);
377                                 break;
378
379                         case PW_MODULE_RETURN_CODE:
380                                 localvp.attribute = da->attr;
381
382                                 /*
383                                  *      See modcall.c for a bit of a hack.
384                                  */
385                                 localvp.vp_integer = request->simul_max;
386                                 break;
387
388                         default:
389                                 return 0; /* not found */
390                                 break;
391                         }
392
393                         localvp.type = da->type;
394                         return valuepair2str(out, outlen, &localvp,
395                                              da->type, func);
396                 }
397
398                 /*
399                  *      Not found, die.
400                  */
401                 return 0;
402         }
403
404         if (!vps) return 0;     /* silently fail */
405
406         /*
407          *      Convert the VP to a string, and return it.
408          */
409         return valuepair2str(out, outlen, vp, da->type, func);
410 }
411
412 #ifdef HAVE_REGEX_H
413 /*
414  *      Pull %{0} to %{8} out of the packet.
415  */
416 static size_t xlat_regex(void *instance, REQUEST *request,
417                          char *fmt, char *out, size_t outlen,
418                          RADIUS_ESCAPE_STRING func)
419 {
420         char *regex;
421
422         /*
423          *      We cheat: fmt is "0" to "8", but those numbers
424          *      are already in the "instance".
425          */
426         fmt = fmt;              /* -Wunused */
427         func = func;            /* -Wunused FIXME: do escaping? */
428
429         regex = request_data_reference(request, request,
430                                  REQUEST_DATA_REGEX | *(int *)instance);
431         if (!regex) return 0;
432
433         /*
434          *      Copy UP TO "freespace" bytes, including
435          *      a zero byte.
436          */
437         strlcpy(out, regex, outlen);
438         return strlen(out);
439 }
440 #endif                          /* HAVE_REGEX_H */
441
442
443 /*
444  *      Change the debugging level.
445  */
446 static size_t xlat_debug(UNUSED void *instance, REQUEST *request,
447                           char *fmt, char *out, size_t outlen,
448                           UNUSED RADIUS_ESCAPE_STRING func)
449 {
450         int level = 0;
451
452         if (*fmt) level = atoi(fmt);
453
454         if (level == 0) {
455                 request->options = RAD_REQUEST_OPTION_NONE;
456                 request->radlog = NULL;
457         } else {
458                 if (level > 4) level = 4;
459
460                 request->options = level;
461                 request->radlog = radlog_request;
462         }
463
464         snprintf(out, outlen, "%d", level);
465         return strlen(out);
466 }
467
468
469 /*
470  *      Calculate the MD5 hash of a string.
471  */
472 static size_t xlat_md5(UNUSED void *instance, REQUEST *request,
473                        char *fmt, char *out, size_t outlen,
474                        UNUSED RADIUS_ESCAPE_STRING func)
475 {
476         int i;
477         uint8_t digest[16];
478         FR_MD5_CTX ctx;
479         char buffer[1024];
480
481         if (!radius_xlat(buffer, sizeof(buffer), fmt, request, func)) {
482                 *out = '\0';
483                 return 0;
484         }
485
486         fr_MD5Init(&ctx);
487         fr_MD5Update(&ctx, (void *) buffer, strlen(buffer));
488         fr_MD5Final(digest, &ctx);
489
490         if (outlen < 33) {
491                 snprintf(out, outlen, "md5_overflow");
492                 return strlen(out);
493         }
494
495         for (i = 0; i < 16; i++) {
496                 snprintf(out + i * 2, 3, "%02x", digest[i]);
497         }
498
499         return strlen(out);
500 }
501
502 /*
503  *      Compare two xlat_t structs, based ONLY on the module name.
504  */
505 static int xlat_cmp(const void *a, const void *b)
506 {
507         if (((const xlat_t *)a)->length != ((const xlat_t *)b)->length) {
508                 return ((const xlat_t *)a)->length - ((const xlat_t *)b)->length;
509         }
510
511         return memcmp(((const xlat_t *)a)->module,
512                       ((const xlat_t *)b)->module,
513                       ((const xlat_t *)a)->length);
514 }
515
516
517 /*
518  *      find the appropriate registered xlat function.
519  */
520 static xlat_t *xlat_find(const char *module)
521 {
522         xlat_t my_xlat;
523
524         /*
525          *      Look for dictionary attributes first.
526          */
527         if ((dict_attrbyname(module) != NULL) ||
528             (strchr(module, '[') != NULL) ||
529             (strchr(module, '#') != NULL)) {
530                 module = "request";
531         }
532
533         strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
534         my_xlat.length = strlen(my_xlat.module);
535
536         return rbtree_finddata(xlat_root, &my_xlat);
537 }
538
539
540 /*
541  *      Register an xlat function.
542  */
543 int xlat_register(const char *module, RAD_XLAT_FUNC func, void *instance)
544 {
545         xlat_t  *c;
546         xlat_t  my_xlat;
547
548         if ((module == NULL) || (strlen(module) == 0)) {
549                 DEBUG("xlat_register: Invalid module name");
550                 return -1;
551         }
552
553         /*
554          *      First time around, build up the tree...
555          *
556          *      FIXME: This code should be hoisted out of this function,
557          *      and into a global "initialization".  But it isn't critical...
558          */
559         if (!xlat_root) {
560                 int i;
561 #ifdef HAVE_REGEX_H
562                 char buffer[2];
563 #endif
564
565                 xlat_root = rbtree_create(xlat_cmp, free, 0);
566                 if (!xlat_root) {
567                         DEBUG("xlat_register: Failed to create tree.");
568                         return -1;
569                 }
570
571                 /*
572                  *      Register the internal packet xlat's.
573                  */
574                 for (i = 0; internal_xlat[i] != NULL; i++) {
575                         xlat_register(internal_xlat[i], xlat_packet, &xlat_inst[i]);
576                         c = xlat_find(internal_xlat[i]);
577                         rad_assert(c != NULL);
578                         c->internal = TRUE;
579                 }
580
581                 /*
582                  *      New name: "control"
583                  */
584                 xlat_register("control", xlat_packet, &xlat_inst[0]);
585                 c = xlat_find("control");
586                 rad_assert(c != NULL);
587                 c->internal = TRUE;
588
589 #ifdef HAVE_REGEX_H
590                 /*
591                  *      Register xlat's for regexes.
592                  */
593                 buffer[1] = '\0';
594                 for (i = 0; i <= REQUEST_MAX_REGEX; i++) {
595                         buffer[0] = '0' + i;
596                         xlat_register(buffer, xlat_regex, &xlat_inst[i]);
597                         c = xlat_find(buffer);
598                         rad_assert(c != NULL);
599                         c->internal = TRUE;
600                 }
601 #endif /* HAVE_REGEX_H */
602
603
604                 xlat_register("debug", xlat_debug, &xlat_inst[0]);
605                 c = xlat_find("debug");
606                 rad_assert(c != NULL);
607                 c->internal = TRUE;
608
609                 xlat_register("md5", xlat_md5, &xlat_inst[0]);
610                 c = xlat_find("md5");
611                 rad_assert(c != NULL);
612                 c->internal = TRUE;
613         }
614
615         /*
616          *      If it already exists, replace the instance.
617          */
618         strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
619         my_xlat.length = strlen(my_xlat.module);
620         c = rbtree_finddata(xlat_root, &my_xlat);
621         if (c) {
622                 if (c->internal) {
623                         DEBUG("xlat_register: Cannot re-define internal xlat");
624                         return -1;
625                 }
626
627                 c->do_xlat = func;
628                 c->instance = instance;
629                 return 0;
630         }
631
632         /*
633          *      Doesn't exist.  Create it.
634          */
635         c = rad_malloc(sizeof(*c));
636         memset(c, 0, sizeof(*c));
637
638         c->do_xlat = func;
639         strlcpy(c->module, module, sizeof(c->module));
640         c->length = strlen(c->module);
641         c->instance = instance;
642
643         rbtree_insert(xlat_root, c);
644
645         return 0;
646 }
647
648 /*
649  *      Unregister an xlat function.
650  *
651  *      We can only have one function to call per name, so the
652  *      passing of "func" here is extraneous.
653  */
654 void xlat_unregister(const char *module, RAD_XLAT_FUNC func)
655 {
656         rbnode_t        *node;
657         xlat_t          my_xlat;
658
659         func = func;            /* -Wunused */
660
661         if (!module) return;
662
663         strlcpy(my_xlat.module, module, sizeof(my_xlat.module));
664         my_xlat.length = strlen(my_xlat.module);
665
666         node = rbtree_find(xlat_root, &my_xlat);
667         if (!node) return;
668
669         rbtree_delete(xlat_root, node);
670 }
671
672 /*
673  *      De-register all xlat functions,
674  *      used mainly for debugging.
675  */
676 void xlat_free(void)
677 {
678         rbtree_free(xlat_root);
679 }
680
681
682 /*
683  *      Decode an attribute name into a string.
684  */
685 static int decode_attribute(const char **from, char **to, int freespace,
686                              REQUEST *request,
687                              RADIUS_ESCAPE_STRING func)
688 {
689         int     do_length = 0;
690         char    *xlat_name, *xlat_string;
691         char *p, *q, *l, *next = NULL;
692         int retlen=0;
693         const xlat_t *c;
694         int varlen;
695         char buffer[8192];
696
697         q = *to;
698
699         *q = '\0';
700
701         /*
702          *      Copy the input string to an intermediate buffer where
703          *      we can mangle it.
704          */
705         varlen = rad_copy_variable(buffer, *from);
706         if (varlen < 0) {
707                 RDEBUG2("Badly formatted variable: %s", *from);
708                 return -1;
709         }
710         *from += varlen;
711
712         /*
713          *      Kill the %{} around the data we are looking for.
714          */
715         p = buffer;
716         p[varlen - 1] = '\0';   /*  */
717         p += 2;
718         if (*p == '#') {
719                 p++;
720                 do_length = 1;
721         }
722
723         /*
724          *      Handle %{%{foo}:-%{bar}}, which is useful, too.
725          *
726          *      Did I mention that this parser is garbage?
727          */
728         if ((p[0] == '%') && (p[1] == '{')) {
729                 int len1, len2;
730                 int expand2 = FALSE;
731
732                 /*
733                  *      'p' is after the start of 'buffer', so we can
734                  *      safely do this.
735                  */
736                 len1 = rad_copy_variable(buffer, p);
737                 if (len1 < 0) {
738                         RDEBUG2("Badly formatted variable: %s", p);
739                         return -1;
740                 }
741
742                 /*
743                  *      They did %{%{foo}}, which is stupid, but allowed.
744                  */
745                 if (!p[len1]) {
746                         RDEBUG2("Improperly nested variable; %%{%s}", p);
747                         return -1;
748                 }
749
750                 /*
751                  *      It SHOULD be %{%{foo}:-%{bar}}.  If not, it's
752                  *      an error.
753                  */
754                 if ((p[len1] != ':') || (p[len1 + 1] != '-')) {
755                         RDEBUG2("No trailing :- after variable at %s", p);
756                         return -1;
757                 }
758
759                 /*
760                  *      Parse the second bit.  The second bit can be
761                  *      either %{foo}, or a string "foo", or a string
762                  *      'foo', or just a bare word: foo
763                  */
764                 p += len1 + 2;
765                 l = buffer + len1 + 1;
766
767                 if ((p[0] == '%') && (p[1] == '{')) {
768                         len2 = rad_copy_variable(l, p);
769
770                         if (len2 < 0) {
771                                 RDEBUG2("Invalid text after :- at %s", p);
772                                 return -1;
773                         }
774                         p += len2;
775                         expand2 = TRUE;
776
777                 } else if ((p[0] == '"') || p[0] == '\'') {
778                         getstring(&p, l, strlen(l));
779
780                 } else {
781                         l = p;
782                 }
783
784                 /*
785                  *      Expand the first one.  If we did, exit the
786                  *      conditional.
787                  */
788                 retlen = radius_xlat(q, freespace, buffer, request, func);
789                 if (retlen) {
790                         q += retlen;
791                         goto done;
792                 }
793
794                 RDEBUG2("\t... expanding second conditional");
795                 /*
796                  *      Expand / copy the second string if required.
797                  */
798                 if (expand2) {
799                         retlen = radius_xlat(q, freespace, l,
800                                             request, func);
801                         if (retlen) {
802                                 q += retlen;
803                         }
804                 } else {
805                         strlcpy(q, l, freespace);
806                         q += strlen(q);
807                 }
808
809                 /*
810                  *      Else the output is an empty string.
811                  */
812                 goto done;
813         }
814
815         /*
816          *      See if we're supposed to expand a module name.
817          */
818         xlat_name = NULL;
819         for (l = p; *l != '\0'; l++) {
820                 if (*l == '\\') {
821                         l++;
822                         continue;
823                 }
824
825                 if (*l == ':') {
826                         xlat_name = p; /* start of name */
827                         *l = '\0';
828                         p = l + 1;
829                         break;
830                 }
831
832                 /*
833                  *      Module names can't have spaces.
834                  */
835                 if ((*l == ' ') || (*l == '\t')) break;
836         }
837
838         /*
839          *      %{name} is a simple attribute reference,
840          *      or regex reference.
841          */
842         if (!xlat_name) {
843                 xlat_name = xlat_string = p;
844                 goto do_xlat;
845         }
846
847         /*
848          *      Maybe it's the old-style %{foo:-bar}
849          */
850         if (*p == '-') {
851                 RDEBUG2("WARNING: Deprecated conditional expansion \":-\".  See \"man unlang\" for details");
852                 p++;
853
854                 xlat_string = xlat_name;
855                 next = p;
856                 goto do_xlat;
857         }
858
859         /*
860          *      FIXME: For backwards "WTF" compatibility, check for
861          *      {...}, (after the :), and copy that, too.
862          */
863
864         /* module name, followed by (possibly) per-module string */
865         xlat_string = p;
866         
867 do_xlat:
868         if ((c = xlat_find(xlat_name)) != NULL) {
869                 if (!c->internal) RDEBUG3("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
870                                           c->module, xlat_string);
871                 retlen = c->do_xlat(c->instance, request, xlat_string,
872                                     q, freespace, func);
873                 if (retlen > 0) {
874                         if (do_length) {
875                                 snprintf(q, freespace, "%d", retlen);
876                                 retlen = strlen(q);
877                         }
878
879                 } else if (next) {
880                         /*
881                          *      Expand the second bit.
882                          */
883                         RDEBUG2("\t... expanding second conditional");
884                         retlen = radius_xlat(q, freespace, next, request, func);
885                 }
886                 q += retlen;
887
888         } else {
889                 /*
890                  *      No attribute by that name, return an error.
891                  */
892                 RDEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
893                 return -1;
894         }
895
896 done:
897         *to = q;
898         return 0;
899 }
900
901 /*
902  *  If the caller doesn't pass xlat an escape function, then
903  *  we use this one.  It simplifies the coding, as the check for
904  *  func == NULL only happens once.
905  */
906 static size_t xlat_copy(char *out, size_t outlen, const char *in)
907 {
908         int freespace = outlen;
909
910         rad_assert(outlen > 0);
911
912         while ((*in) && (freespace > 1)) {
913                 /*
914                  *  Copy data.
915                  *
916                  *  FIXME: Do escaping of bad stuff!
917                  */
918                 *(out++) = *(in++);
919
920                 freespace--;
921         }
922         *out = '\0';
923
924         return (outlen - freespace); /* count does not include NUL */
925 }
926
927 /*
928  *      Replace %<whatever> in a string.
929  *
930  *      See 'doc/variables.txt' for more information.
931  */
932 int radius_xlat(char *out, int outlen, const char *fmt,
933                 REQUEST *request, RADIUS_ESCAPE_STRING func)
934 {
935         int c, len, freespace;
936         const char *p;
937         char *q;
938         char *nl;
939         VALUE_PAIR *tmp;
940         struct tm *TM, s_TM;
941         char tmpdt[40]; /* For temporary storing of dates */
942         int openbraces=0;
943
944         /*
945          *      Catch bad modules.
946          */
947         if (!fmt || !out || !request) return 0;
948
949         /*
950          *  Ensure that we always have an escaping function.
951          */
952         if (func == NULL) {
953                 func = xlat_copy;
954         }
955
956         q = out;
957         p = fmt;
958         while (*p) {
959                 /* Calculate freespace in output */
960                 freespace = outlen - (q - out);
961                 if (freespace <= 1)
962                         break;
963                 c = *p;
964
965                 if ((c != '%') && (c != '$') && (c != '\\')) {
966                         /*
967                          * We check if we're inside an open brace.  If we are
968                          * then we assume this brace is NOT literal, but is
969                          * a closing brace and apply it
970                          */
971                         if ((c == '}') && openbraces) {
972                                 openbraces--;
973                                 p++; /* skip it */
974                                 continue;
975                         }
976                         *q++ = *p++;
977                         continue;
978                 }
979
980                 /*
981                  *      There's nothing after this character, copy
982                  *      the last '%' or "$' or '\\' over to the output
983                  *      buffer, and exit.
984                  */
985                 if (*++p == '\0') {
986                         *q++ = c;
987                         break;
988                 }
989
990                 if (c == '\\') {
991                         switch(*p) {
992                         case '\\':
993                                 *q++ = *p;
994                                 break;
995                         case 't':
996                                 *q++ = '\t';
997                                 break;
998                         case 'n':
999                                 *q++ = '\n';
1000                                 break;
1001                         default:
1002                                 *q++ = c;
1003                                 *q++ = *p;
1004                                 break;
1005                         }
1006                         p++;
1007
1008                 } else if (c == '%') switch(*p) {
1009                         case '{':
1010                                 p--;
1011                                 if (decode_attribute(&p, &q, freespace, request, func) < 0) return 0;
1012                                 break;
1013
1014                         case '%':
1015                                 *q++ = *p++;
1016                                 break;
1017                         case 'a': /* Protocol: */
1018                                 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL, 0),PW_TYPE_INTEGER, func);
1019                                 p++;
1020                                 break;
1021                         case 'c': /* Callback-Number */
1022                                 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER, 0),PW_TYPE_STRING, func);
1023                                 p++;
1024                                 break;
1025                         case 'd': /* request day */
1026                                 TM = localtime_r(&request->timestamp, &s_TM);
1027                                 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
1028                                 if (len > 0) {
1029                                         strlcpy(q, tmpdt, freespace);
1030                                         q += strlen(q);
1031                                 }
1032                                 p++;
1033                                 break;
1034                         case 'f': /* Framed IP address */
1035                                 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS, 0),PW_TYPE_IPADDR, func);
1036                                 p++;
1037                                 break;
1038                         case 'i': /* Calling station ID */
1039                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID, 0),PW_TYPE_STRING, func);
1040                                 p++;
1041                                 break;
1042                         case 'l': /* request timestamp */
1043                                 snprintf(tmpdt, sizeof(tmpdt), "%lu",
1044                                          (unsigned long) request->timestamp);
1045                                 strlcpy(q,tmpdt,freespace);
1046                                 q += strlen(q);
1047                                 p++;
1048                                 break;
1049                         case 'm': /* request month */
1050                                 TM = localtime_r(&request->timestamp, &s_TM);
1051                                 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
1052                                 if (len > 0) {
1053                                         strlcpy(q, tmpdt, freespace);
1054                                         q += strlen(q);
1055                                 }
1056                                 p++;
1057                                 break;
1058                         case 'n': /* NAS IP address */
1059                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS, 0),PW_TYPE_IPADDR, func);
1060                                 p++;
1061                                 break;
1062                         case 'p': /* Port number */
1063                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT, 0),PW_TYPE_INTEGER, func);
1064                                 p++;
1065                                 break;
1066                         case 's': /* Speed */
1067                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO, 0),PW_TYPE_STRING, func);
1068                                 p++;
1069                                 break;
1070                         case 't': /* request timestamp */
1071                                 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
1072                                 nl = strchr(tmpdt, '\n');
1073                                 if (nl) *nl = '\0';
1074                                 strlcpy(q, tmpdt, freespace);
1075                                 q += strlen(q);
1076                                 p++;
1077                                 break;
1078                         case 'u': /* User name */
1079                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME, 0),PW_TYPE_STRING, func);
1080                                 p++;
1081                                 break;
1082                         case 'A': /* radacct_dir */
1083                                 strlcpy(q,radacct_dir,freespace);
1084                                 q += strlen(q);
1085                                 p++;
1086                                 break;
1087                         case 'C': /* ClientName */
1088                                 strlcpy(q,request->client->shortname,freespace);
1089                                 q += strlen(q);
1090                                 p++;
1091                                 break;
1092                         case 'D': /* request date */
1093                                 TM = localtime_r(&request->timestamp, &s_TM);
1094                                 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
1095                                 if (len > 0) {
1096                                         strlcpy(q, tmpdt, freespace);
1097                                         q += strlen(q);
1098                                 }
1099                                 p++;
1100                                 break;
1101                         case 'H': /* request hour */
1102                                 TM = localtime_r(&request->timestamp, &s_TM);
1103                                 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
1104                                 if (len > 0) {
1105                                         strlcpy(q, tmpdt, freespace);
1106                                         q += strlen(q);
1107                                 }
1108                                 p++;
1109                                 break;
1110                         case 'L': /* radlog_dir */
1111                                 strlcpy(q,radlog_dir,freespace);
1112                                 q += strlen(q);
1113                                 p++;
1114                                 break;
1115                         case 'M': /* MTU */
1116                                 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU, 0),PW_TYPE_INTEGER, func);
1117                                 p++;
1118                                 break;
1119                         case 'R': /* radius_dir */
1120                                 strlcpy(q,radius_dir,freespace);
1121                                 q += strlen(q);
1122                                 p++;
1123                                 break;
1124                         case 'S': /* request timestamp in SQL format*/
1125                                 TM = localtime_r(&request->timestamp, &s_TM);
1126                                 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1127                                 if (len > 0) {
1128                                         strlcpy(q, tmpdt, freespace);
1129                                         q += strlen(q);
1130                                 }
1131                                 p++;
1132                                 break;
1133                         case 'T': /* request timestamp */
1134                                 TM = localtime_r(&request->timestamp, &s_TM);
1135                                 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1136                                 if (len > 0) {
1137                                         strlcpy(q, tmpdt, freespace);
1138                                         q += strlen(q);
1139                                 }
1140                                 p++;
1141                                 break;
1142                         case 'U': /* Stripped User name */
1143                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME, 0),PW_TYPE_STRING, func);
1144                                 p++;
1145                                 break;
1146                         case 'V': /* Request-Authenticator */
1147                                 strlcpy(q,"Verified",freespace);
1148                                 q += strlen(q);
1149                                 p++;
1150                                 break;
1151                         case 'Y': /* request year */
1152                                 TM = localtime_r(&request->timestamp, &s_TM);
1153                                 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1154                                 if (len > 0) {
1155                                         strlcpy(q, tmpdt, freespace);
1156                                         q += strlen(q);
1157                                 }
1158                                 p++;
1159                                 break;
1160                         case 'Z': /* Full request pairs except password */
1161                                 tmp = request->packet->vps;
1162                                 while (tmp && (freespace > 3)) {
1163                                         if (tmp->attribute != PW_USER_PASSWORD) {
1164                                                 *q++ = '\t';
1165                                                 len = vp_prints(q, freespace - 2, tmp);
1166                                                 q += len;
1167                                                 freespace -= (len + 2);
1168                                                 *q++ = '\n';
1169                                         }
1170                                         tmp = tmp->next;
1171                                 }
1172                                 p++;
1173                                 break;
1174                         default:
1175                                 RDEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1176                                 if (freespace > 2) {
1177                                         *q++ = '%';
1178                                         *q++ = *p++;
1179                                 }
1180                                 break;
1181                 }
1182         }
1183         *q = '\0';
1184
1185         RDEBUG2("\texpand: %s -> %s", fmt, out);
1186
1187         return strlen(out);
1188 }