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