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