Improved sentence in rlm_perl comment
[freeradius.git] / src / modules / rlm_perl / rlm_perl.c
1 /*
2  *   This program is is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License as published by
4  *   the Free Software Foundation; either version 2 of the License, or (at
5  *   your option) any later version.
6  *
7  *   This program is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *   GNU General Public License for more details.
11  *
12  *   You should have received a copy of the GNU General Public License
13  *   along with this program; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16
17 /**
18  * $Id$
19  * @file rlm_perl.c
20  * @brief Translates requests between the server an a perl interpreter.
21  *
22  * @copyright 2002,2006  The FreeRADIUS server project
23  * @copyright 2002  Boian Jordanov <bjordanov@orbitel.bg>
24  */
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/rad_assert.h>
30
31 #ifdef INADDR_ANY
32 #  undef INADDR_ANY
33 #endif
34 #include <EXTERN.h>
35 #include <perl.h>
36 #include <XSUB.h>
37 #include <dlfcn.h>
38 #include <semaphore.h>
39
40 #ifdef __APPLE__
41 extern char **environ;
42 #endif
43
44 /*
45  *      Define a structure for our module configuration.
46  *
47  *      These variables do not need to be in a structure, but it's
48  *      a lot cleaner to do so, and a pointer to the structure can
49  *      be used as the instance handle.
50  */
51 typedef struct rlm_perl_t {
52         /* Name of the perl module */
53         char const      *module;
54
55         /* Name of the functions for each module method */
56         char const      *func_authorize;
57         char const      *func_authenticate;
58         char const      *func_accounting;
59         char const      *func_start_accounting;
60         char const      *func_stop_accounting;
61         char const      *func_preacct;
62         char const      *func_checksimul;
63         char const      *func_detach;
64         char const      *func_xlat;
65 #ifdef WITH_PROXY
66         char const      *func_pre_proxy;
67         char const      *func_post_proxy;
68 #endif
69         char const      *func_post_auth;
70 #ifdef WITH_COA
71         char const      *func_recv_coa;
72         char const      *func_send_coa;
73 #endif
74         char const      *xlat_name;
75         char const      *perl_flags;
76         PerlInterpreter *perl;
77         bool            perl_parsed;
78         pthread_key_t   *thread_key;
79
80 #ifdef USE_ITHREADS
81         pthread_mutex_t clone_mutex;
82 #endif
83
84         HV              *rad_perlconf_hv;       //!< holds "config" items (perl %RAD_PERLCONF hash).
85
86 } rlm_perl_t;
87 /*
88  *      A mapping of configuration file names to internal variables.
89  */
90 #define RLM_PERL_CONF(_x) { "func_" STRINGIFY(_x), PW_TYPE_STRING, \
91                         offsetof(rlm_perl_t,func_##_x), NULL, STRINGIFY(_x)}
92
93 static const CONF_PARSER module_config[] = {
94         { "module", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, rlm_perl_t, module), NULL },
95         { "filename", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_REQUIRED, rlm_perl_t, module), NULL },
96
97         RLM_PERL_CONF(authorize),
98         RLM_PERL_CONF(authenticate),
99         RLM_PERL_CONF(post_auth),
100         RLM_PERL_CONF(accounting),
101         RLM_PERL_CONF(preacct),
102         RLM_PERL_CONF(checksimul),
103         RLM_PERL_CONF(detach),
104         RLM_PERL_CONF(xlat),
105
106 #ifdef WITH_PROXY
107         RLM_PERL_CONF(pre_proxy),
108         RLM_PERL_CONF(post_proxy),
109 #endif
110 #ifdef WITH_COA
111         RLM_PERL_CONF(recv_coa),
112         RLM_PERL_CONF(send_coa),
113 #endif
114         { "perl_flags", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_perl_t, perl_flags), NULL },
115
116         { "func_start_accounting", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_perl_t, func_start_accounting), NULL },
117
118         { "func_stop_accounting", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_perl_t, func_stop_accounting), NULL },
119         CONF_PARSER_TERMINATOR
120 };
121
122 /*
123  * man perlembed
124  */
125 EXTERN_C void boot_DynaLoader(pTHX_ CV* cv);
126
127 #ifdef USE_ITHREADS
128 #  define dl_librefs "DynaLoader::dl_librefs"
129 #  define dl_modules "DynaLoader::dl_modules"
130 static void rlm_perl_clear_handles(pTHX)
131 {
132         AV *librefs = get_av(dl_librefs, false);
133         if (librefs) {
134                 av_clear(librefs);
135         }
136 }
137
138 static void **rlm_perl_get_handles(pTHX)
139 {
140         I32 i;
141         AV *librefs = get_av(dl_librefs, false);
142         AV *modules = get_av(dl_modules, false);
143         void **handles;
144
145         if (!librefs) return NULL;
146
147         if (!(AvFILL(librefs) >= 0)) {
148                 return NULL;
149         }
150
151         handles = (void **)rad_malloc(sizeof(void *) * (AvFILL(librefs)+2));
152
153         for (i = 0; i <= AvFILL(librefs); i++) {
154                 void *handle;
155                 SV *handle_sv = *av_fetch(librefs, i, false);
156                 if (!handle_sv) {
157                         ERROR("Could not fetch $%s[%d]!", dl_librefs, (int)i);
158                         continue;
159                 }
160                 handle = (void *)SvIV(handle_sv);
161
162                 if (handle) handles[i] = handle;
163         }
164
165         av_clear(modules);
166         av_clear(librefs);
167
168         handles[i] = (void *)0;
169
170         return handles;
171 }
172
173 static void rlm_perl_close_handles(void **handles)
174 {
175         int i;
176
177         if (!handles) {
178                 return;
179         }
180
181         for (i = 0; handles[i]; i++) {
182                 DEBUG("Close %p", handles[i]);
183                 dlclose(handles[i]);
184         }
185
186         free(handles);
187 }
188
189 DIAG_OFF(shadow)
190 static void rlm_perl_destruct(PerlInterpreter *perl)
191 {
192         dTHXa(perl);
193
194         PERL_SET_CONTEXT(perl);
195
196         PL_perl_destruct_level = 2;
197
198         PL_origenviron = environ;
199
200
201         {
202                 dTHXa(perl);
203         }
204         /*
205          * FIXME: This shouldn't happen
206          *
207          */
208         while (PL_scopestack_ix > 1) {
209                 LEAVE;
210         }
211
212         perl_destruct(perl);
213         perl_free(perl);
214 }
215 DIAG_ON(shadow)
216
217 static void rlm_destroy_perl(PerlInterpreter *perl)
218 {
219         void    **handles;
220
221         dTHXa(perl);
222         PERL_SET_CONTEXT(perl);
223
224         handles = rlm_perl_get_handles(aTHX);
225         if (handles) rlm_perl_close_handles(handles);
226         rlm_perl_destruct(perl);
227 }
228
229 /* Create Key */
230 static void rlm_perl_make_key(pthread_key_t *key)
231 {
232         pthread_key_create(key, (void (*)(void *))rlm_destroy_perl);
233 }
234
235 static PerlInterpreter *rlm_perl_clone(PerlInterpreter *perl, pthread_key_t *key)
236 {
237         int ret;
238
239         PerlInterpreter *interp;
240         UV clone_flags = 0;
241
242         PERL_SET_CONTEXT(perl);
243
244         interp = pthread_getspecific(*key);
245         if (interp) return interp;
246
247         interp = perl_clone(perl, clone_flags);
248         {
249                 dTHXa(interp);
250         }
251 #  if PERL_REVISION >= 5 && PERL_VERSION <8
252         call_pv("CLONE",0);
253 #  endif
254         ptr_table_free(PL_ptr_table);
255         PL_ptr_table = NULL;
256
257         PERL_SET_CONTEXT(aTHX);
258         rlm_perl_clear_handles(aTHX);
259
260         ret = pthread_setspecific(*key, interp);
261         if (ret != 0) {
262                 DEBUG("rlm_perl: Failed associating interpretor with thread %s", fr_syserror(ret));
263
264                 rlm_perl_destruct(interp);
265                 return NULL;
266         }
267
268         return interp;
269 }
270 #endif
271
272 /*
273  *      This is wrapper for radlog
274  *      Now users can call radiusd::radlog(level,msg) wich is the same
275  *      as calling radlog from C code.
276  */
277 static XS(XS_radiusd_radlog)
278 {
279         dXSARGS;
280         if (items !=2)
281                 croak("Usage: radiusd::radlog(level, message)");
282         {
283                 int     level;
284                 char    *msg;
285
286                 level = (int) SvIV(ST(0));
287                 msg   = (char *) SvPV(ST(1), PL_na);
288
289                 /*
290                  *      Because 'msg' is a 'char *', we don't want '%s', etc.
291                  *      in it to give us printf-style vulnerabilities.
292                  */
293                 radlog(level, "rlm_perl: %s", msg);
294         }
295         XSRETURN_NO;
296 }
297
298 static void xs_init(pTHX)
299 {
300         char const *file = __FILE__;
301
302         /* DynaLoader is a special case */
303         newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
304
305         newXS("radiusd::radlog",XS_radiusd_radlog, "rlm_perl");
306 }
307
308 /*
309  *      The xlat function
310  */
311 static ssize_t perl_xlat(void *instance, REQUEST *request, char const *fmt, char *out, size_t freespace)
312 {
313
314         rlm_perl_t      *inst = (rlm_perl_t *) instance;
315         char            *tmp;
316         char const      *p, *q;
317         int             count;
318         size_t          ret = 0;
319         STRLEN          n_a;
320
321 #ifdef USE_ITHREADS
322         PerlInterpreter *interp;
323
324         pthread_mutex_lock(&inst->clone_mutex);
325         interp = rlm_perl_clone(inst->perl, inst->thread_key);
326         {
327                 dTHXa(interp);
328                 PERL_SET_CONTEXT(interp);
329         }
330         pthread_mutex_unlock(&inst->clone_mutex);
331 #else
332         PERL_SET_CONTEXT(inst->perl);
333 #endif
334         {
335                 dSP;
336                 ENTER;SAVETMPS;
337
338                 PUSHMARK(SP);
339
340                 p = q = fmt;
341                 while (*p == ' ') {
342                         p++;
343                         q++;
344                 }
345                 while (*q) {
346                         if (*q == ' ') {
347                                 XPUSHs(sv_2mortal(newSVpvn(p, q - p)));
348                                 p = q + 1;
349
350                                 /*
351                                  *      Don't use an empty string
352                                  */
353                                 while (*p == ' ') p++;
354                                 q = p;
355                         }
356                         q++;
357                 }
358
359                 /*
360                  *      And the last bit.
361                  */
362                 if (*p) {
363                         XPUSHs(sv_2mortal(newSVpvn(p, strlen(p))));
364                 }
365
366                 PUTBACK;
367
368                 count = call_pv(inst->func_xlat, G_SCALAR | G_EVAL);
369
370                 SPAGAIN;
371                 if (SvTRUE(ERRSV)) {
372                         REDEBUG("Exit %s", SvPV(ERRSV,n_a));
373                         (void)POPs;
374                 } else if (count > 0) {
375                         tmp = POPp;
376                         strlcpy(out, tmp, freespace);
377                         ret = strlen(out);
378
379                         RDEBUG("Len is %zu , out is %s freespace is %zu", ret, out, freespace);
380                 }
381
382                 PUTBACK ;
383                 FREETMPS ;
384                 LEAVE ;
385
386         }
387
388         return ret;
389 }
390
391 /*
392  *      Parse a configuration section, and populate a HV.
393  *      This function is recursively called (allows to have nested hashes.)
394  */
395 static void perl_parse_config(CONF_SECTION *cs, int lvl, HV *rad_hv)
396 {
397         if (!cs || !rad_hv) return;
398
399         int indent_section = (lvl + 1) * 4;
400         int indent_item = (lvl + 2) * 4;
401
402         DEBUG("%*s%s {", indent_section, " ", cf_section_name1(cs));
403
404         CONF_ITEM *ci = NULL;
405
406         while ((ci = cf_item_find_next(cs, ci))) {
407                 /*
408                  *  This is a section.
409                  *  Create a new HV, store it as a reference in current HV,
410                  *  Then recursively call perl_parse_config with this section and the new HV.
411                  */
412                 if (cf_item_is_section(ci)) {
413                         CONF_SECTION    *sub_cs = cf_item_to_section(ci);
414                         char const      *key = cf_section_name1(sub_cs); /* hash key */
415                         HV              *sub_hv;
416                         SV              *ref;
417
418                         if (!key) continue;
419
420                         if (hv_exists(rad_hv, key, strlen(key))) {
421                                 WARN("rlm_perl: Ignoring duplicate config section '%s'", key);
422                                 continue;
423                         }
424
425                         sub_hv = newHV();
426                         ref = newRV_inc((SV*) sub_hv);
427
428                         (void)hv_store(rad_hv, key, strlen(key), ref, 0);
429
430                         perl_parse_config(sub_cs, lvl + 1, sub_hv);
431                 } else if (cf_item_is_pair(ci)){
432                         CONF_PAIR       *cp = cf_item_to_pair(ci);
433                         char const      *key = cf_pair_attr(cp);        /* hash key */
434                         char const      *value = cf_pair_value(cp);     /* hash value */
435
436                         if (!key || !value) continue;
437
438                         /*
439                          *  This is an item.
440                          *  Store item attr / value in current HV.
441                          */
442                         if (hv_exists(rad_hv, key, strlen(key))) {
443                                 WARN("rlm_perl: Ignoring duplicate config item '%s'", key);
444                                 continue;
445                         }
446
447                         (void)hv_store(rad_hv, key, strlen(key), newSVpvn(value, strlen(value)), 0);
448
449                         DEBUG("%*s%s = %s", indent_item, " ", key, value);
450                 }
451         }
452
453         DEBUG("%*s}", indent_section, " ");
454 }
455
456 static int mod_bootstrap(CONF_SECTION *conf, void *instance)
457 {
458         rlm_perl_t      *inst = instance;
459
460         char const      *xlat_name;
461
462         xlat_name = cf_section_name2(conf);
463         if (!xlat_name) xlat_name = cf_section_name1(conf);
464
465         xlat_register(xlat_name, perl_xlat, NULL, inst);
466
467         return 0;
468 }
469
470 /*
471  *      Do any per-module initialization that is separate to each
472  *      configured instance of the module.  e.g. set up connections
473  *      to external databases, read configuration files, set up
474  *      dictionary entries, etc.
475  *
476  *      If configuration information is given in the config section
477  *      that must be referenced in later calls, store a handle to it
478  *      in *instance otherwise put a null pointer there.
479  *
480  *      Setup a hashes wich we will use later
481  *      parse a module and give him a chance to live
482  *
483  */
484 static int mod_instantiate(CONF_SECTION *conf, void *instance)
485 {
486         rlm_perl_t      *inst = instance;
487         AV              *end_AV;
488
489         char const      **embed_c;      /* Stupid Perl and lack of const consistency */
490         char            **embed;
491         char            **envp = NULL;
492         int             exitstatus = 0, argc=0;
493         char            arg[] = "0";
494
495         CONF_SECTION    *cs;
496
497 #ifdef USE_ITHREADS
498         /*
499          *      Create pthread key. This key will be stored in instance
500          */
501         pthread_mutex_init(&inst->clone_mutex, NULL);
502
503         inst->thread_key = rad_malloc(sizeof(*inst->thread_key));
504         memset(inst->thread_key,0,sizeof(*inst->thread_key));
505
506         rlm_perl_make_key(inst->thread_key);
507 #endif
508
509         /*
510          *      Setup the argument array we pass to the perl interpreter
511          */
512         MEM(embed_c = talloc_zero_array(inst, char const *, 4));
513         memcpy(&embed, &embed_c, sizeof(embed));
514         embed_c[0] = NULL;
515         if (inst->perl_flags) {
516                 embed_c[1] = inst->perl_flags;
517                 embed_c[2] = inst->module;
518                 embed_c[3] = arg;
519                 argc = 4;
520         } else {
521                 embed_c[1] = inst->module;
522                 embed_c[2] = arg;
523                 argc = 3;
524         }
525
526         /*
527          *      Create tweak the server's environment to support
528          *      perl. Docs say only call this once... Oops.
529          */
530         PERL_SYS_INIT3(&argc, &embed, &envp);
531
532         /*
533          *      Allocate a new perl interpreter to do the parsing
534          */
535         if ((inst->perl = perl_alloc()) == NULL) {
536                 ERROR("rlm_perl: No memory for allocating new perl !");
537                 return -1;
538         }
539         perl_construct(inst->perl);     /* ...and initialise it */
540
541 #ifdef USE_ITHREADS
542         PL_perl_destruct_level = 2;
543
544         {
545                 dTHXa(inst->perl);
546         }
547         PERL_SET_CONTEXT(inst->perl);
548 #endif
549
550 #if PERL_REVISION >= 5 && PERL_VERSION >=8
551         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
552 #endif
553
554         exitstatus = perl_parse(inst->perl, xs_init, argc, embed, NULL);
555
556         end_AV = PL_endav;
557         PL_endav = (AV *)NULL;
558
559         if (exitstatus) {
560                 ERROR("rlm_perl: perl_parse failed: %s not found or has syntax errors", inst->module);
561                 return -1;
562         }
563
564         /* parse perl configuration sub-section */
565         cs = cf_section_sub_find(conf, "config");
566         if (cs) {
567                 inst->rad_perlconf_hv = get_hv("RAD_PERLCONF", 1);
568                 perl_parse_config(cs, 0, inst->rad_perlconf_hv);
569         }
570
571         inst->perl_parsed = true;
572         perl_run(inst->perl);
573
574         PL_endav = end_AV;
575
576         return 0;
577 }
578
579 static void perl_vp_to_svpvn_element(REQUEST *request, AV *av, VALUE_PAIR const *vp,
580                                      int *i, const char *hash_name, const char *list_name)
581 {
582         size_t len;
583
584         char buffer[1024];
585
586         switch (vp->da->type) {
587         case PW_TYPE_STRING:
588                 RDEBUG("$%s{'%s'}[%i] = &%s:%s -> '%s'", hash_name, vp->da->name, *i,
589                        list_name, vp->da->name, vp->vp_strvalue);
590                 av_push(av, newSVpvn(vp->vp_strvalue, vp->vp_length));
591                 break;
592
593         default:
594                 len = vp_prints_value(buffer, sizeof(buffer), vp, 0);
595                 RDEBUG("$%s{'%s'}[%i] = &%s:%s -> '%s'", hash_name, vp->da->name, *i,
596                        list_name, vp->da->name, buffer);
597                 av_push(av, newSVpvn(buffer, truncate_len(len, sizeof(buffer))));
598                 break;
599         }
600         (*i)++;
601 }
602
603 /*
604  *      get the vps and put them in perl hash
605  *      If one VP have multiple values it is added as array_ref
606  *      Example for this is Cisco-AVPair that holds multiple values.
607  *      Which will be available as array_ref in $RAD_REQUEST{'Cisco-AVPair'}
608  */
609 static void perl_store_vps(UNUSED TALLOC_CTX *ctx, REQUEST *request, VALUE_PAIR **vps, HV *rad_hv,
610                            const char *hash_name, const char *list_name)
611 {
612         VALUE_PAIR *vp;
613
614         hv_undef(rad_hv);
615
616         vp_cursor_t cursor;
617
618         RINDENT();
619         fr_pair_list_sort(vps, fr_pair_cmp_by_da_tag);
620         for (vp = fr_cursor_init(&cursor, vps);
621              vp;
622              vp = fr_cursor_next(&cursor)) {
623                 VALUE_PAIR *next;
624
625                 char const *name;
626                 char namebuf[256];
627                 char buffer[1024];
628
629                 size_t len;
630
631                 /*
632                  *      Tagged attributes are added to the hash with name
633                  *      <attribute>:<tag>, others just use the normal attribute
634                  *      name as the key.
635                  */
636                 if (vp->da->flags.has_tag && (vp->tag != TAG_ANY)) {
637                         snprintf(namebuf, sizeof(namebuf), "%s:%d", vp->da->name, vp->tag);
638                         name = namebuf;
639                 } else {
640                         name = vp->da->name;
641                 }
642
643                 /*
644                  *      We've sorted by type, then tag, so attributes of the
645                  *      same type/tag should follow on from each other.
646                  */
647                 if ((next = fr_cursor_next_peek(&cursor)) && ATTRIBUTE_EQ(vp, next)) {
648                         int i = 0;
649                         AV *av;
650
651                         av = newAV();
652
653                         perl_vp_to_svpvn_element(request, av, vp, &i, hash_name, list_name);
654                         do {
655                                 perl_vp_to_svpvn_element(request, av, next, &i, hash_name, list_name);
656                                 fr_cursor_next(&cursor);
657                         } while ((next = fr_cursor_next_peek(&cursor)) && ATTRIBUTE_EQ(vp, next));
658                         (void)hv_store(rad_hv, name, strlen(name), newRV_noinc((SV *)av), 0);
659
660                         continue;
661                 }
662
663                 /*
664                  *      It's a normal single valued attribute
665                  */
666                 switch (vp->da->type) {
667                 case PW_TYPE_STRING:
668                         RDEBUG("$%s{'%s'} = &%s:%s -> '%s'", hash_name, vp->da->name, list_name,
669                                vp->da->name, vp->vp_strvalue);
670                         (void)hv_store(rad_hv, name, strlen(name), newSVpvn(vp->vp_strvalue, vp->vp_length), 0);
671                         break;
672
673                 default:
674                         len = vp_prints_value(buffer, sizeof(buffer), vp, 0);
675                         RDEBUG("$%s{'%s'} = &%s:%s -> '%s'", hash_name, vp->da->name,
676                                list_name, vp->da->name, buffer);
677                         (void)hv_store(rad_hv, name, strlen(name),
678                                        newSVpvn(buffer, truncate_len(len, sizeof(buffer))), 0);
679                         break;
680                 }
681         }
682         REXDENT();
683 }
684
685 /*
686  *
687  *     Verify that a Perl SV is a string and save it in FreeRadius
688  *     Value Pair Format
689  *
690  */
691 static void pairadd_sv(TALLOC_CTX *ctx, REQUEST *request, VALUE_PAIR **vps, char *key, SV *sv, FR_TOKEN op,
692                       const char *hash_name, const char *list_name)
693 {
694         char            *val = NULL;
695         VALUE_PAIR      *vp;
696         STRLEN len;
697
698         if (!SvOK(sv)) {
699         fail:
700                 REDEBUG("Failed to create pair &%s:%s %s $%s{'%s'} -> '%s'", list_name, key,
701                         fr_int2str(fr_tokens, op, "<INVALID>"), hash_name, key, (val ? val : "undef"));
702                 return;
703         }
704         val = SvPV(sv, len);
705         vp = fr_pair_make(ctx, vps, key, NULL, op);
706         if (!vp) goto fail;
707
708         switch (vp->da->type) {
709         case PW_TYPE_STRING:
710                 fr_pair_value_bstrncpy(vp, val, len);
711                 break;
712
713         default:
714                 if (fr_pair_value_from_str(vp, val, len) < 0) goto fail;
715         }
716
717         RDEBUG("&%s:%s %s $%s{'%s'} -> '%s'", list_name, key, fr_int2str(fr_tokens, op, "<INVALID>"),
718                hash_name, key, val);
719 }
720
721 /*
722  *     Gets the content from hashes
723  */
724 static void get_hv_content(TALLOC_CTX *ctx, REQUEST *request, HV *my_hv, VALUE_PAIR **vps,
725                           const char *hash_name, const char *list_name)
726 {
727         SV              *res_sv, **av_sv;
728         AV              *av;
729         char            *key;
730         I32             key_len, len, i, j;
731
732         *vps = NULL;
733         for (i = hv_iterinit(my_hv); i > 0; i--) {
734                 res_sv = hv_iternextsv(my_hv,&key,&key_len);
735                 if (SvROK(res_sv) && (SvTYPE(SvRV(res_sv)) == SVt_PVAV)) {
736                         av = (AV*)SvRV(res_sv);
737                         len = av_len(av);
738                         for (j = 0; j <= len; j++) {
739                                 av_sv = av_fetch(av, j, 0);
740                                 pairadd_sv(ctx, request, vps, key, *av_sv, T_OP_ADD, hash_name, list_name);
741                         }
742                 } else {
743                         pairadd_sv(ctx, request, vps, key, res_sv, T_OP_EQ, hash_name, list_name);
744                 }
745         }
746 }
747
748 /*
749  *      Call the function_name inside the module
750  *      Store all vps in hashes %RAD_CHECK %RAD_REPLY %RAD_REQUEST
751  *
752  */
753 static int do_perl(void *instance, REQUEST *request, char const *function_name)
754 {
755
756         rlm_perl_t      *inst = instance;
757         VALUE_PAIR      *vp;
758         int             exitstatus=0, count;
759         STRLEN          n_a;
760
761         HV              *rad_reply_hv;
762         HV              *rad_check_hv;
763         HV              *rad_config_hv;
764         HV              *rad_request_hv;
765         HV              *rad_state_hv;
766 #ifdef WITH_PROXY
767         HV              *rad_request_proxy_hv;
768         HV              *rad_request_proxy_reply_hv;
769 #endif
770
771         /*
772          *      Radius has told us to call this function, but none
773          *      is defined.
774          */
775         if (!function_name) return RLM_MODULE_FAIL;
776
777 #ifdef USE_ITHREADS
778         pthread_mutex_lock(&inst->clone_mutex);
779
780         PerlInterpreter *interp;
781
782         interp = rlm_perl_clone(inst->perl,inst->thread_key);
783         {
784                 dTHXa(interp);
785                 PERL_SET_CONTEXT(interp);
786         }
787
788         pthread_mutex_unlock(&inst->clone_mutex);
789 #else
790         PERL_SET_CONTEXT(inst->perl);
791 #endif
792
793         {
794                 dSP;
795
796                 ENTER;
797                 SAVETMPS;
798
799                 rad_reply_hv = get_hv("RAD_REPLY", 1);
800                 rad_check_hv = get_hv("RAD_CHECK", 1);
801                 rad_config_hv = get_hv("RAD_CONFIG", 1);
802                 rad_request_hv = get_hv("RAD_REQUEST", 1);
803                 rad_state_hv = get_hv("RAD_STATE", 1);
804
805                 perl_store_vps(request->packet, request, &request->packet->vps, rad_request_hv, "RAD_REQUEST", "request");
806                 perl_store_vps(request->reply, request, &request->reply->vps, rad_reply_hv, "RAD_REPLY", "reply");
807                 perl_store_vps(request, request, &request->config, rad_check_hv, "RAD_CHECK", "control");
808                 perl_store_vps(request, request, &request->config, rad_config_hv, "RAD_CONFIG", "control");
809                 perl_store_vps(request->state_ctx, request, &request->state, rad_state_hv, "RAD_STATE", "session-state");
810
811 #ifdef WITH_PROXY
812                 rad_request_proxy_hv = get_hv("RAD_REQUEST_PROXY",1);
813                 rad_request_proxy_reply_hv = get_hv("RAD_REQUEST_PROXY_REPLY",1);
814
815                 if (request->proxy != NULL) {
816                         perl_store_vps(request->proxy, request, &request->proxy->vps, rad_request_proxy_hv,
817                                        "RAD_REQUEST_PROXY", "proxy-request");
818                 } else {
819                         hv_undef(rad_request_proxy_hv);
820                 }
821
822                 if (request->proxy_reply != NULL) {
823                         perl_store_vps(request->proxy_reply, request, &request->proxy_reply->vps,
824                                        rad_request_proxy_reply_hv, "RAD_REQUEST_PROXY_REPLY", "proxy-reply");
825                 } else {
826                         hv_undef(rad_request_proxy_reply_hv);
827                 }
828 #endif
829
830                 PUSHMARK(SP);
831                 /*
832                  * This way %RAD_xx can be pushed onto stack as sub parameters.
833                  * XPUSHs( newRV_noinc((SV *)rad_request_hv) );
834                  * XPUSHs( newRV_noinc((SV *)rad_reply_hv) );
835                  * XPUSHs( newRV_noinc((SV *)rad_check_hv) );
836                  * PUTBACK;
837                  */
838
839                 count = call_pv(function_name, G_SCALAR | G_EVAL | G_NOARGS);
840
841                 SPAGAIN;
842
843                 if (SvTRUE(ERRSV)) {
844                         RDEBUG("perl_embed:: module = %s , func = %s exit status= %s\n",
845                                inst->module, function_name, SvPV(ERRSV,n_a));
846                         (void)POPs;
847                 }
848
849                 if (count == 1) {
850                         exitstatus = POPi;
851                         if (exitstatus >= 100 || exitstatus < 0) {
852                                 exitstatus = RLM_MODULE_FAIL;
853                         }
854                 }
855
856
857                 PUTBACK;
858                 FREETMPS;
859                 LEAVE;
860
861                 vp = NULL;
862                 get_hv_content(request->packet, request, rad_request_hv, &vp, "RAD_REQUEST", "request");
863                 if (vp) {
864                         fr_pair_list_free(&request->packet->vps);
865                         request->packet->vps = vp;
866                         vp = NULL;
867
868                         /*
869                          *      Update cached copies
870                          */
871                         request->username = fr_pair_find_by_num(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
872                         request->password = fr_pair_find_by_num(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
873                         if (!request->password)
874                                 request->password = fr_pair_find_by_num(request->packet->vps, PW_CHAP_PASSWORD, 0, TAG_ANY);
875                 }
876
877                 get_hv_content(request->reply, request, rad_reply_hv, &vp, "RAD_REPLY", "reply");
878                 if (vp) {
879                         fr_pair_list_free(&request->reply->vps);
880                         request->reply->vps = vp;
881                         vp = NULL;
882                 }
883
884                 get_hv_content(request, request, rad_check_hv, &vp, "RAD_CHECK", "control");
885                 if (vp) {
886                         fr_pair_list_free(&request->config);
887                         request->config = vp;
888                         vp = NULL;
889                 }
890
891                 get_hv_content(request->state_ctx, request, rad_state_hv, &vp, "RAD_STATE", "session-state");
892                 if (vp) {
893                         fr_pair_list_free(&request->state);
894                         request->state = vp;
895                         vp = NULL;
896                 }
897
898 #ifdef WITH_PROXY
899                 if (request->proxy) {
900                         get_hv_content(request->proxy, request, rad_request_proxy_hv, &vp,
901                             "RAD_REQUEST_PROXY", "proxy-request");
902                         if (vp) {
903                                 fr_pair_list_free(&request->proxy->vps);
904                                 request->proxy->vps = vp;
905                                 vp = NULL;
906                         }
907                 }
908
909                 if (request->proxy_reply) {
910                         get_hv_content(request->proxy_reply, request, rad_request_proxy_reply_hv, &vp,
911                             "RAD_REQUEST_PROXY_REPLY", "proxy-reply");
912                         if (vp) {
913                                 fr_pair_list_free(&request->proxy_reply->vps);
914                                 request->proxy_reply->vps = vp;
915                                 vp = NULL;
916                         }
917                 }
918 #endif
919
920         }
921         return exitstatus;
922 }
923
924 #define RLM_PERL_FUNC(_x) static rlm_rcode_t CC_HINT(nonnull) mod_##_x(void *instance, REQUEST *request) \
925         {                                                               \
926                 return do_perl(instance, request,                       \
927                                ((rlm_perl_t *)instance)->func_##_x); \
928         }
929
930 RLM_PERL_FUNC(authorize)
931 RLM_PERL_FUNC(authenticate)
932 RLM_PERL_FUNC(post_auth)
933
934 RLM_PERL_FUNC(checksimul)
935
936 #ifdef WITH_PROXY
937 RLM_PERL_FUNC(pre_proxy)
938 RLM_PERL_FUNC(post_proxy)
939 #endif
940
941 #ifdef WITH_COA
942 RLM_PERL_FUNC(recv_coa)
943 RLM_PERL_FUNC(send_coa)
944 #endif
945
946 RLM_PERL_FUNC(preacct)
947
948 /*
949  *      Write accounting information to this modules database.
950  */
951 static rlm_rcode_t CC_HINT(nonnull) mod_accounting(void *instance, REQUEST *request)
952 {
953         VALUE_PAIR      *pair;
954         int             acctstatustype=0;
955
956         if ((pair = fr_pair_find_by_num(request->packet->vps, PW_ACCT_STATUS_TYPE, 0, TAG_ANY)) != NULL) {
957                 acctstatustype = pair->vp_integer;
958         } else {
959                 RDEBUG("Invalid Accounting Packet");
960                 return RLM_MODULE_INVALID;
961         }
962
963         switch (acctstatustype) {
964         case PW_STATUS_START:
965                 if (((rlm_perl_t *)instance)->func_start_accounting) {
966                         return do_perl(instance, request,
967                                        ((rlm_perl_t *)instance)->func_start_accounting);
968                 } else {
969                         return do_perl(instance, request,
970                                        ((rlm_perl_t *)instance)->func_accounting);
971                 }
972
973         case PW_STATUS_STOP:
974                 if (((rlm_perl_t *)instance)->func_stop_accounting) {
975                         return do_perl(instance, request,
976                                        ((rlm_perl_t *)instance)->func_stop_accounting);
977                 } else {
978                         return do_perl(instance, request,
979                                        ((rlm_perl_t *)instance)->func_accounting);
980                 }
981
982         default:
983                 return do_perl(instance, request,
984                                ((rlm_perl_t *)instance)->func_accounting);
985         }
986 }
987
988
989 /*
990  * Detach a instance give a chance to a module to make some internal setup ...
991  */
992 DIAG_OFF(nested-externs)
993 static int mod_detach(void *instance)
994 {
995         rlm_perl_t      *inst = (rlm_perl_t *) instance;
996         int             exitstatus = 0, count = 0;
997
998         if (inst->rad_perlconf_hv != NULL) hv_undef(inst->rad_perlconf_hv);
999
1000         if (inst->perl_parsed && inst->func_detach) {
1001                 dTHXa(inst->perl);
1002                 PERL_SET_CONTEXT(inst->perl);
1003                 {
1004                         dSP; ENTER; SAVETMPS;
1005                         PUSHMARK(SP);
1006
1007                         count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1008                         SPAGAIN;
1009
1010                         if (count == 1) {
1011                                 exitstatus = POPi;
1012                                 if (exitstatus >= 100 || exitstatus < 0) {
1013                                         exitstatus = RLM_MODULE_FAIL;
1014                                 }
1015                         }
1016                         PUTBACK;
1017                         FREETMPS;
1018                         LEAVE;
1019                 }
1020         }
1021
1022 #ifdef USE_ITHREADS
1023         rlm_perl_destruct(inst->perl);
1024         pthread_mutex_destroy(&inst->clone_mutex);
1025 #else
1026         perl_destruct(inst->perl);
1027         perl_free(inst->perl);
1028 #endif
1029
1030         PERL_SYS_TERM();
1031         return exitstatus;
1032 }
1033 DIAG_ON(nested-externs)
1034
1035 /*
1036  *      The module name should be the only globally exported symbol.
1037  *      That is, everything else should be 'static'.
1038  *
1039  *      If the module needs to temporarily modify it's instantiation
1040  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
1041  *      The server will then take care of ensuring that the module
1042  *      is single-threaded.
1043  */
1044 extern module_t rlm_perl;
1045 module_t rlm_perl = {
1046         .magic          = RLM_MODULE_INIT,
1047         .name           = "perl",
1048 #ifdef USE_ITHREADS
1049         .type           = RLM_TYPE_THREAD_SAFE,
1050 #else
1051         .type           = RLM_TYPE_THREAD_UNSAFE,
1052 #endif
1053         .inst_size      = sizeof(rlm_perl_t),
1054         .config         = module_config,
1055         .bootstrap      = mod_bootstrap,
1056         .instantiate    = mod_instantiate,
1057         .detach         = mod_detach,
1058         .methods = {
1059                 [MOD_AUTHENTICATE]      = mod_authenticate,
1060                 [MOD_AUTHORIZE]         = mod_authorize,
1061                 [MOD_PREACCT]           = mod_preacct,
1062                 [MOD_ACCOUNTING]        = mod_accounting,
1063                 [MOD_SESSION]           = mod_checksimul,
1064 #ifdef WITH_PROXY
1065                 [MOD_PRE_PROXY]         = mod_pre_proxy,
1066                 [MOD_POST_PROXY]        = mod_post_proxy,
1067 #endif
1068                 [MOD_POST_AUTH]         = mod_post_auth,
1069 #ifdef WITH_COA
1070                 [MOD_RECV_COA]          = mod_recv_coa,
1071                 [MOD_SEND_COA]          = mod_send_coa
1072 #endif
1073         },
1074 };