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