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