Now that we have request->client, we don't need client_find()
[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 done;
626                 }
627
628                 if ((p[len1] != ':') || (p[len1 + 1] != '-')) {
629                         DEBUG2("No trailing :- after variable at %s", p);
630                         goto 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 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 done;
660                 }
661
662                 mylen = radius_xlat(q, freespace, first, request, func);
663                 free(first);
664                 if (mylen) {
665                         free(second);
666
667                         q += mylen;
668                         goto done;
669                 }
670
671                 if (!expand2) {
672                         strlcpy(q, second, freespace);
673                         q += strlen(q);
674                 } else {
675                         mylen = radius_xlat(q, freespace, second,
676                                             request, func);
677                         free(second);
678                         if (mylen) {
679                                 q += mylen;
680                                 goto done;
681                         }
682                 }
683
684                 /*
685                  *      Else the output is an empty string.
686                  */
687                 goto done;
688         }
689
690
691         /*
692          *      First, copy the xlat key name to one buffer
693          */
694         while (*p && (*p != '}') && (*p != ':')) {
695                 *pa++ = *p++;
696
697                 if (pa >= (xlat_name + sizeof(xlat_name) - 1)) {
698                         /*
699                          *      Skip to the end of the input
700                          */
701                         p += strlen(p);
702                         DEBUG("xlat: Module name is too long in string %%%s",
703                               *from);
704                         goto done;
705                 }
706         }
707         *pa = '\0';
708
709         if (!*p) {
710                 DEBUG("xlat: Invalid syntax in %s", *from);
711
712                 /*
713                  *      %{name} is a simple attribute reference,
714                  *      or regex reference.
715                  */
716         } else if (*p == '}') {
717                 openbraces--;
718                 rad_assert(openbraces == *open_p);
719
720                 p++;
721                 xlat_string = xlat_name;
722                 goto do_xlat;
723
724         } else if ((p[0] == ':') && (p[1] == '-')) { /* handle ':- */
725                 DEBUG2("WARNING: Deprecated conditional expansion \":-\".  See \"man unlang\" for details");
726                 p += 2;
727                 xlat_string = xlat_name;
728                 goto do_xlat;
729
730         } else {      /* module name, followed by per-module string */
731                 int stop = 0;
732                 int delimitbrace = *open_p;
733
734                 rad_assert(*p == ':');
735                 p++;                    /* skip the ':' */
736
737                 /*
738                  *  If there's a brace immediately following the colon,
739                  *  then we've chosen to delimite the per-module string,
740                  *  so keep track of that.
741                  */
742                 if (*p == '{') {
743                         delimitbrace = openbraces;
744                         openbraces++;
745                         p++;
746                 }
747
748                 xlat_string = rad_malloc(strlen(p) + 1); /* always returns */
749                 free_xlat_string = TRUE;
750                 pa = xlat_string;
751
752                 /*
753                  *  Copy over the rest of the string, which is per-module
754                  *  data.
755                  */
756                 while (*p && !stop) {
757                         switch(*p) {
758
759                                 /*
760                                  *      What the heck is this supposed
761                                  *      to be doing?
762                                  */
763                         case '\\':
764                                 p++; /* skip it */
765                                 *pa++ = *p++;
766                                 break;
767
768                         case ':':
769                                 if (!spaces && p[1] == '-') {
770                                         p += 2;
771                                         stop = 1;
772                                         break;
773                                 }
774                                 *pa++ = *p++;
775                                 break;
776
777                                 /*
778                                  *      This is pretty hokey...  we
779                                  *      should use the functions in
780                                  *      util.c
781                                  */
782                         case '{':
783                                 openbraces++;
784                                 *pa++ = *p++;
785                                 break;
786
787                         case '}':
788                                 openbraces--;
789                                 if (openbraces == delimitbrace) {
790                                         p++;
791                                         stop=1;
792                                 } else {
793                                         *pa++ = *p++;
794                                 }
795                                 break;
796
797                         case ' ':
798                         case '\t':
799                                 spaces = TRUE;
800                                 /* FALL-THROUGH */
801
802                         default:
803                                 *pa++ = *p++;
804                                 break;
805                         }
806                 }
807
808                 *pa = '\0';
809
810                 /*
811                  *      Now check to see if we're at the end of the string
812                  *      we were sent.  If we're not, check for :-
813                  */
814                 if (openbraces == delimitbrace) {
815                         if (p[0] == ':' && p[1] == '-') {
816                                 p += 2;
817                         }
818                 }
819
820                 /*
821                  *      Look up almost everything in the new tree of xlat
822                  *      functions.  This makes it a little quicker...
823                  */
824         do_xlat:
825                 if ((c = xlat_find(xlat_name)) != NULL) {
826                         if (!c->internal) DEBUG3("radius_xlat: Running registered xlat function of module %s for string \'%s\'",
827                                                 c->module, xlat_string);
828                         retlen = c->do_xlat(c->instance, request, xlat_string,
829                                             q, freespace, func);
830                         /* If retlen is 0, treat it as not found */
831                         if (retlen > 0) found = 1;
832
833 #ifndef NDEBUG
834                 } else {
835                         /*
836                          *      No attribute by that name, return an error.
837                          */
838                         DEBUG2("WARNING: Unknown module \"%s\" in string expansion \"%%%s\"", xlat_name, *from);
839 #endif
840                 }
841         }
842
843         /*
844          * Skip to last '}' if attr is found
845          * The rest of the stuff within the braces is
846          * useless if we found what we need
847          */
848         if (found) {
849                 if (do_length) {
850                         snprintf(q, freespace, "%d", retlen);
851                         retlen = strlen(q);
852                 }
853
854                 q += retlen;
855
856                 while((*p != '\0') && (openbraces > *open_p)) {
857                         /*
858                          *      Handle escapes outside of the loop.
859                          */
860                         if (*p == '\\') {
861                                 p++;
862                                 if (!*p) break;
863                                 p++; /* get & ignore next character */
864                                 continue;
865                         }
866
867                         switch (*p) {
868                         default:
869                                 break;
870
871                                 /*
872                                  *  Bare brace
873                                  */
874                         case '{':
875                                 openbraces++;
876                                 break;
877
878                         case '}':
879                                 openbraces--;
880                                 break;
881                         }
882                         p++;    /* skip the character */
883                 }
884         }
885
886         done:
887         if (free_xlat_string) free(xlat_string);
888
889         *open_p = openbraces;
890         *from = p;
891         *to = q;
892 }
893
894 /*
895  *  If the caller doesn't pass xlat an escape function, then
896  *  we use this one.  It simplifies the coding, as the check for
897  *  func == NULL only happens once.
898  */
899 static size_t xlat_copy(char *out, size_t outlen, const char *in)
900 {
901         int freespace = outlen;
902
903         rad_assert(outlen > 0);
904
905         while ((*in) && (freespace > 1)) {
906                 /*
907                  *  Copy data.
908                  *
909                  *  FIXME: Do escaping of bad stuff!
910                  */
911                 *(out++) = *(in++);
912
913                 freespace--;
914         }
915         *out = '\0';
916
917         return (outlen - freespace); /* count does not include NUL */
918 }
919
920 /*
921  *      Replace %<whatever> in a string.
922  *
923  *      See 'doc/variables.txt' for more information.
924  */
925 int radius_xlat(char *out, int outlen, const char *fmt,
926                 REQUEST *request, RADIUS_ESCAPE_STRING func)
927 {
928         int c, len, freespace;
929         const char *p;
930         char *q;
931         char *nl;
932         VALUE_PAIR *tmp;
933         struct tm *TM, s_TM;
934         char tmpdt[40]; /* For temporary storing of dates */
935         int openbraces=0;
936
937         /*
938          *      Catch bad modules.
939          */
940         if (!fmt || !out || !request) return 0;
941
942         /*
943          *  Ensure that we always have an escaping function.
944          */
945         if (func == NULL) {
946                 func = xlat_copy;
947         }
948
949         q = out;
950         p = fmt;
951         while (*p) {
952                 /* Calculate freespace in output */
953                 freespace = outlen - (q - out);
954                 if (freespace <= 1)
955                         break;
956                 c = *p;
957
958                 if ((c != '%') && (c != '$') && (c != '\\')) {
959                         /*
960                          * We check if we're inside an open brace.  If we are
961                          * then we assume this brace is NOT literal, but is
962                          * a closing brace and apply it
963                          */
964                         if ((c == '}') && openbraces) {
965                                 openbraces--;
966                                 p++; /* skip it */
967                                 continue;
968                         }
969                         *q++ = *p++;
970                         continue;
971                 }
972
973                 /*
974                  *      There's nothing after this character, copy
975                  *      the last '%' or "$' or '\\' over to the output
976                  *      buffer, and exit.
977                  */
978                 if (*++p == '\0') {
979                         *q++ = c;
980                         break;
981                 }
982
983                 if (c == '\\') {
984                         switch(*p) {
985                         case '\\':
986                                 *q++ = *p;
987                                 break;
988                         case 't':
989                                 *q++ = '\t';
990                                 break;
991                         case 'n':
992                                 *q++ = '\n';
993                                 break;
994                         default:
995                                 *q++ = c;
996                                 *q++ = *p;
997                                 break;
998                         }
999                         p++;
1000
1001                 } else if (c == '%') switch(*p) {
1002                         case '{':
1003                                 decode_attribute(&p, &q, freespace, &openbraces, request, func);
1004                                 break;
1005
1006                         case '%':
1007                                 *q++ = *p++;
1008                                 break;
1009                         case 'a': /* Protocol: */
1010                                 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_PROTOCOL),PW_TYPE_INTEGER, func);
1011                                 p++;
1012                                 break;
1013                         case 'c': /* Callback-Number */
1014                                 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_CALLBACK_NUMBER),PW_TYPE_STRING, func);
1015                                 p++;
1016                                 break;
1017                         case 'd': /* request day */
1018                                 TM = localtime_r(&request->timestamp, &s_TM);
1019                                 len = strftime(tmpdt, sizeof(tmpdt), "%d", TM);
1020                                 if (len > 0) {
1021                                         strlcpy(q, tmpdt, freespace);
1022                                         q += strlen(q);
1023                                 }
1024                                 p++;
1025                                 break;
1026                         case 'f': /* Framed IP address */
1027                                 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_IP_ADDRESS),PW_TYPE_IPADDR, func);
1028                                 p++;
1029                                 break;
1030                         case 'i': /* Calling station ID */
1031                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CALLING_STATION_ID),PW_TYPE_STRING, func);
1032                                 p++;
1033                                 break;
1034                         case 'l': /* request timestamp */
1035                                 snprintf(tmpdt, sizeof(tmpdt), "%lu",
1036                                          (unsigned long) request->received.tv_sec);
1037                                 strlcpy(q,tmpdt,freespace);
1038                                 q += strlen(q);
1039                                 p++;
1040                                 break;
1041                         case 'm': /* request month */
1042                                 TM = localtime_r(&request->timestamp, &s_TM);
1043                                 len = strftime(tmpdt, sizeof(tmpdt), "%m", TM);
1044                                 if (len > 0) {
1045                                         strlcpy(q, tmpdt, freespace);
1046                                         q += strlen(q);
1047                                 }
1048                                 p++;
1049                                 break;
1050                         case 'n': /* NAS IP address */
1051                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_IP_ADDRESS),PW_TYPE_IPADDR, func);
1052                                 p++;
1053                                 break;
1054                         case 'p': /* Port number */
1055                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_NAS_PORT),PW_TYPE_INTEGER, func);
1056                                 p++;
1057                                 break;
1058                         case 's': /* Speed */
1059                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_CONNECT_INFO),PW_TYPE_STRING, func);
1060                                 p++;
1061                                 break;
1062                         case 't': /* request timestamp */
1063                                 CTIME_R(&request->timestamp, tmpdt, sizeof(tmpdt));
1064                                 nl = strchr(tmpdt, '\n');
1065                                 if (nl) *nl = '\0';
1066                                 strlcpy(q, tmpdt, freespace);
1067                                 q += strlen(q);
1068                                 p++;
1069                                 break;
1070                         case 'u': /* User name */
1071                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_USER_NAME),PW_TYPE_STRING, func);
1072                                 p++;
1073                                 break;
1074                         case 'A': /* radacct_dir */
1075                                 strlcpy(q,radacct_dir,freespace);
1076                                 q += strlen(q);
1077                                 p++;
1078                                 break;
1079                         case 'C': /* ClientName */
1080                                 strlcpy(q,request->client->shortname,freespace);
1081                                 q += strlen(q);
1082                                 p++;
1083                                 break;
1084                         case 'D': /* request date */
1085                                 TM = localtime_r(&request->timestamp, &s_TM);
1086                                 len = strftime(tmpdt, sizeof(tmpdt), "%Y%m%d", TM);
1087                                 if (len > 0) {
1088                                         strlcpy(q, tmpdt, freespace);
1089                                         q += strlen(q);
1090                                 }
1091                                 p++;
1092                                 break;
1093                         case 'H': /* request hour */
1094                                 TM = localtime_r(&request->timestamp, &s_TM);
1095                                 len = strftime(tmpdt, sizeof(tmpdt), "%H", TM);
1096                                 if (len > 0) {
1097                                         strlcpy(q, tmpdt, freespace);
1098                                         q += strlen(q);
1099                                 }
1100                                 p++;
1101                                 break;
1102                         case 'L': /* radlog_dir */
1103                                 strlcpy(q,radlog_dir,freespace);
1104                                 q += strlen(q);
1105                                 p++;
1106                                 break;
1107                         case 'M': /* MTU */
1108                                 q += valuepair2str(q,freespace,pairfind(request->reply->vps,PW_FRAMED_MTU),PW_TYPE_INTEGER, func);
1109                                 p++;
1110                                 break;
1111                         case 'R': /* radius_dir */
1112                                 strlcpy(q,radius_dir,freespace);
1113                                 q += strlen(q);
1114                                 p++;
1115                                 break;
1116                         case 'S': /* request timestamp in SQL format*/
1117                                 TM = localtime_r(&request->timestamp, &s_TM);
1118                                 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d %H:%M:%S", TM);
1119                                 if (len > 0) {
1120                                         strlcpy(q, tmpdt, freespace);
1121                                         q += strlen(q);
1122                                 }
1123                                 p++;
1124                                 break;
1125                         case 'T': /* request timestamp */
1126                                 TM = localtime_r(&request->timestamp, &s_TM);
1127                                 len = strftime(tmpdt, sizeof(tmpdt), "%Y-%m-%d-%H.%M.%S.000000", TM);
1128                                 if (len > 0) {
1129                                         strlcpy(q, tmpdt, freespace);
1130                                         q += strlen(q);
1131                                 }
1132                                 p++;
1133                                 break;
1134                         case 'U': /* Stripped User name */
1135                                 q += valuepair2str(q,freespace,pairfind(request->packet->vps,PW_STRIPPED_USER_NAME),PW_TYPE_STRING, func);
1136                                 p++;
1137                                 break;
1138                         case 'V': /* Request-Authenticator */
1139                                 strlcpy(q,"Verified",freespace);
1140                                 q += strlen(q);
1141                                 p++;
1142                                 break;
1143                         case 'Y': /* request year */
1144                                 TM = localtime_r(&request->timestamp, &s_TM);
1145                                 len = strftime(tmpdt, sizeof(tmpdt), "%Y", TM);
1146                                 if (len > 0) {
1147                                         strlcpy(q, tmpdt, freespace);
1148                                         q += strlen(q);
1149                                 }
1150                                 p++;
1151                                 break;
1152                         case 'Z': /* Full request pairs except password */
1153                                 tmp = request->packet->vps;
1154                                 while (tmp && (freespace > 3)) {
1155                                         if (tmp->attribute != PW_USER_PASSWORD) {
1156                                                 *q++ = '\t';
1157                                                 len = vp_prints(q, freespace - 2, tmp);
1158                                                 q += len;
1159                                                 freespace -= (len + 2);
1160                                                 *q++ = '\n';
1161                                         }
1162                                         tmp = tmp->next;
1163                                 }
1164                                 p++;
1165                                 break;
1166                         default:
1167                                 DEBUG2("WARNING: Unknown variable '%%%c': See 'doc/variables.txt'", *p);
1168                                 if (freespace > 2) {
1169                                         *q++ = '%';
1170                                         *q++ = *p++;
1171                                 }
1172                                 break;
1173                 }
1174         }
1175         *q = '\0';
1176
1177         DEBUG2("\texpand: %s -> %s", fmt, out);
1178
1179         return strlen(out);
1180 }