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