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