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