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