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