Added additional fix for #348 - each instance will have its own interp and this
[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  The FreeRADIUS server project
21  * Copyright 2002  Boian Jordanov <bjordanov@orbitel.bg>
22  */
23
24 #include <freeradius-devel/autoconf.h>
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29
30 #include <freeradius-devel/radiusd.h>
31 #include <freeradius-devel/modules.h>
32 #include <freeradius-devel/conffile.h>
33
34 #ifdef DEBUG
35 #undef DEBUG
36 #endif
37
38 #ifdef INADDR_ANY
39 #undef INADDR_ANY
40 #endif
41
42 #include <EXTERN.h>
43 #include <perl.h>
44 #include <XSUB.h>
45 #include <dlfcn.h>
46 #include <semaphore.h>
47
48 #ifdef __APPLE__
49 extern char **environ;
50 #endif
51
52 static const char rcsid[] = "$Id$";
53
54 #ifdef USE_ITHREADS
55
56 /*
57  * Pool of Perl's clones (genetically cloned) ;)
58  *
59  */
60 typedef struct pool_handle {
61         struct pool_handle      *next;
62         struct pool_handle      *prev;
63         enum {busy, idle}       status;
64         unsigned int            request_count;
65         PerlInterpreter         *clone;
66         perl_mutex              lock;
67 } POOL_HANDLE;
68
69 typedef struct PERL_POOL {
70         POOL_HANDLE     *head;
71         POOL_HANDLE     *tail;
72
73         int             current_clones;
74         int             active_clones;
75         int             max_clones;
76         int             start_clones;
77         int             min_spare_clones;
78         int             max_spare_clones;
79         int             max_request_per_clone;
80         int             cleanup_delay;
81         enum {yes,no}   detach;
82         perl_mutex      mutex;
83         time_t          time_when_last_added;
84 } PERL_POOL;
85
86 #endif
87
88 /*
89  *      Define a structure for our module configuration.
90  *
91  *      These variables do not need to be in a structure, but it's
92  *      a lot cleaner to do so, and a pointer to the structure can
93  *      be used as the instance handle.
94  */
95 typedef struct perl_inst {
96         /* Name of the perl module */
97         char    *module;
98
99         /* Name of the functions for each module method */
100         char    *func_authorize;
101         char    *func_authenticate;
102         char    *func_accounting;
103         char    *func_start_accounting;
104         char    *func_stop_accounting;
105         char    *func_preacct;
106         char    *func_checksimul;
107         char    *func_detach;
108         char    *func_xlat;
109         char    *func_pre_proxy;
110         char    *func_post_proxy;
111         char    *func_post_auth;
112         char    *xlat_name;
113         char    *perl_flags;
114         PerlInterpreter *perl;
115 #ifdef USE_ITHREADS
116         PERL_POOL       *perl_pool;
117 #endif
118 } PERL_INST;
119 /*
120  *      A mapping of configuration file names to internal variables.
121  *
122  *      Note that the string is dynamically allocated, so it MUST
123  *      be freed.  When the configuration file parse re-reads the string,
124  *      it free's the old one, and strdup's the new one, placing the pointer
125  *      to the strdup'd string into 'config.string'.  This gets around
126  *      buffer over-flows.
127  */
128 static const CONF_PARSER module_config[] = {
129         { "module",  PW_TYPE_FILENAME,
130           offsetof(PERL_INST,module), NULL,  "module"},
131         { "func_authorize", PW_TYPE_STRING_PTR,
132           offsetof(PERL_INST,func_authorize), NULL, "authorize"},
133         { "func_authenticate", PW_TYPE_STRING_PTR,
134           offsetof(PERL_INST,func_authenticate), NULL, "authenticate"},
135         { "func_accounting", PW_TYPE_STRING_PTR,
136           offsetof(PERL_INST,func_accounting), NULL, "accounting"},
137         { "func_preacct", PW_TYPE_STRING_PTR,
138           offsetof(PERL_INST,func_preacct), NULL, "preacct"},
139         { "func_checksimul", PW_TYPE_STRING_PTR,
140           offsetof(PERL_INST,func_checksimul), NULL, "checksimul"},
141         { "func_detach", PW_TYPE_STRING_PTR,
142           offsetof(PERL_INST,func_detach), NULL, "detach"},
143         { "func_xlat", PW_TYPE_STRING_PTR,
144           offsetof(PERL_INST,func_xlat), NULL, "xlat"},
145         { "func_pre_proxy", PW_TYPE_STRING_PTR,
146           offsetof(PERL_INST,func_pre_proxy), NULL, "pre_proxy"},
147         { "func_post_proxy", PW_TYPE_STRING_PTR,
148           offsetof(PERL_INST,func_post_proxy), NULL, "post_proxy"},
149         { "func_post_auth", PW_TYPE_STRING_PTR,
150           offsetof(PERL_INST,func_post_auth), NULL, "post_auth"},
151         { "perl_flags", PW_TYPE_STRING_PTR,
152           offsetof(PERL_INST,perl_flags), NULL, NULL},
153         { "func_start_accounting", PW_TYPE_STRING_PTR,
154           offsetof(PERL_INST,func_start_accounting), NULL, NULL},
155         { "func_stop_accounting", PW_TYPE_STRING_PTR,
156           offsetof(PERL_INST,func_stop_accounting), NULL, NULL},
157
158         { NULL, -1, 0, NULL, NULL }             /* end the list */
159 };
160
161 /*
162  * man perlembed
163  */
164 EXTERN_C void boot_DynaLoader(pTHX_ CV* cv);
165
166 #ifdef USE_ITHREADS
167 /*
168  *      We use one perl to clone from it i.e. main boss
169  *      We clone it for every instance if we have perl
170  *      with -Duseithreads compiled in
171  */
172 static PerlInterpreter  *interp = NULL;
173
174 static const CONF_PARSER pool_conf[] = {
175         { "max_clones", PW_TYPE_INTEGER, offsetof(PERL_POOL, max_clones), NULL,         "32"},
176         { "start_clones",PW_TYPE_INTEGER, offsetof(PERL_POOL, start_clones), NULL,              "32"},
177         { "min_spare_clones",PW_TYPE_INTEGER, offsetof(PERL_POOL, min_spare_clones),NULL,       "0"},
178         { "max_spare_clones",PW_TYPE_INTEGER, offsetof(PERL_POOL,max_spare_clones),NULL,        "32"},
179         { "cleanup_delay",PW_TYPE_INTEGER, offsetof(PERL_POOL,cleanup_delay),NULL,              "5"},
180         { "max_request_per_clone",PW_TYPE_INTEGER, offsetof(PERL_POOL,max_request_per_clone),NULL,      "0"},
181         { NULL, -1, 0, NULL, NULL }             /* end the list */
182 };
183
184
185 #define dl_librefs "DynaLoader::dl_librefs"
186 #define dl_modules "DynaLoader::dl_modules"
187 static void rlm_perl_clear_handles(pTHX)
188 {
189         AV *librefs = get_av(dl_librefs, FALSE);
190         if (librefs) {
191                 av_clear(librefs);
192         }
193 }
194
195 static void **rlm_perl_get_handles(pTHX)
196 {
197         I32 i;
198         AV *librefs = get_av(dl_librefs, FALSE);
199         AV *modules = get_av(dl_modules, FALSE);
200         void **handles;
201
202         if (!librefs) {
203                 radlog(L_ERR,
204                    "Could not get @%s for unloading.\n",
205                    dl_librefs);
206                 return NULL;
207         }
208
209         if (!(AvFILL(librefs) >= 0)) {
210                 return NULL;
211         }
212
213         handles = (void **)rad_malloc(sizeof(void *) * (AvFILL(librefs)+2));
214
215         for (i=0; i<=AvFILL(librefs); i++) {
216                 void *handle;
217                 SV *handle_sv = *av_fetch(librefs, i, FALSE);
218
219                 if(!handle_sv) {
220                     radlog(L_ERR,
221                                "Could not fetch $%s[%d]!\n",
222                                dl_librefs, (int)i);
223                     continue;
224                 }
225                 handle = (void *)SvIV(handle_sv);
226
227                 if (handle) {
228                     handles[i] = handle;
229                 }
230         }
231
232         av_clear(modules);
233         av_clear(librefs);
234
235         handles[i] = (void *)0;
236
237         return handles;
238 }
239
240 static void rlm_perl_close_handles(void **handles)
241 {
242         int i;
243
244         if (!handles) {
245                 return;
246         }
247
248         for (i=0; handles[i]; i++) {
249                 radlog(L_DBG, "close 0x%lx\n", (unsigned long)handles[i]);
250                 dlclose(handles[i]);
251         }
252
253         free(handles);
254 }
255
256 static PerlInterpreter *rlm_perl_clone(PerlInterpreter *perl)
257 {
258         PerlInterpreter *clone;
259         UV clone_flags = 0;
260
261         PERL_SET_CONTEXT(perl);
262
263         clone = perl_clone(perl, clone_flags);
264         {
265                 dTHXa(clone);
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         return clone;
277 }
278
279 static void rlm_perl_destruct(PerlInterpreter *perl)
280 {
281         char **orig_environ = NULL;
282         dTHXa(perl);
283
284         PERL_SET_CONTEXT(perl);
285
286         PL_perl_destruct_level = 2;
287
288         PL_origenviron = environ;
289
290         {
291                 dTHXa(perl);
292         }
293         /*
294          * FIXME: This shouldn't happen
295          *
296          */
297         while (PL_scopestack_ix > 1 ){
298                 LEAVE;
299         }
300
301         perl_destruct(perl);
302         perl_free(perl);
303
304         if (orig_environ) {
305                 environ = orig_environ;
306         }
307 }
308
309 static void rlm_destroy_perl(PerlInterpreter *perl)
310 {
311         void    **handles;
312
313         dTHXa(perl);
314         PERL_SET_CONTEXT(perl);
315
316         handles = rlm_perl_get_handles(aTHX);
317         rlm_perl_destruct(perl);
318         rlm_perl_close_handles(handles);
319 }
320
321 static void delete_pool_handle(POOL_HANDLE *handle, PERL_INST *inst)
322 {
323         POOL_HANDLE *prev;
324         POOL_HANDLE *next;
325
326         prev = handle->prev;
327         next = handle->next;
328
329         if (prev == NULL) {
330                 inst->perl_pool->head = next;
331         } else {
332                 prev->next = next;
333         }
334
335         if (next == NULL) {
336                 inst->perl_pool->tail = prev;
337         } else {
338                 next->prev = prev;
339         }
340         inst->perl_pool->current_clones--;
341         MUTEX_DESTROY(&handle->lock);
342         free(handle);
343 }
344
345 static void move2tail(POOL_HANDLE *handle, PERL_INST *inst)
346 {
347         POOL_HANDLE *prev;
348         POOL_HANDLE *next;
349
350         if (inst->perl_pool->head == NULL) {
351
352                 handle->prev = NULL;
353                 handle->next = NULL;
354                 inst->perl_pool->head = handle;
355                 inst->perl_pool->tail = handle;
356                 return;
357         }
358
359         if (inst->perl_pool->tail == handle) {
360                 return;
361         }
362
363         prev = handle->prev;
364         next = handle->next;
365
366         if ((next != NULL) ||
367                         (prev != NULL)) {
368                 if (next == NULL) {
369                         return;
370                 }
371
372                 if (prev == NULL) {
373                         inst->perl_pool->head = next;
374                         next->prev = NULL;
375
376                 } else {
377
378                         prev->next = next;
379                         next->prev = prev;
380                 }
381         }
382
383         handle->next = NULL;
384         prev = inst->perl_pool->tail;
385
386         inst->perl_pool->tail = handle;
387         handle->prev = prev;
388         prev->next = handle;
389 }
390
391
392 static POOL_HANDLE *pool_grow (PERL_INST *inst) {
393         POOL_HANDLE *handle;
394         time_t  now;
395
396         if (inst->perl_pool->max_clones == inst->perl_pool->current_clones) {
397                 return NULL;
398         }
399         if (inst->perl_pool->detach == yes ) {
400                 return NULL;
401         }
402
403         handle = (POOL_HANDLE *)rad_malloc(sizeof(POOL_HANDLE));
404
405         if (!handle) {
406                 radlog(L_ERR,"Could not find free memory for pool. Aborting");
407                 return NULL;
408         }
409
410         handle->prev = NULL;
411         handle->next = NULL;
412         handle->status = idle;
413         handle->clone = rlm_perl_clone(inst->perl);
414         handle->request_count = 0;
415         MUTEX_INIT(&handle->lock);
416         inst->perl_pool->current_clones++;
417         move2tail(handle, inst);
418
419         now = time(NULL);
420         inst->perl_pool->time_when_last_added = now;
421
422         return handle;
423 }
424
425 static POOL_HANDLE *pool_pop(PERL_INST *inst)
426 {
427         POOL_HANDLE     *handle;
428         POOL_HANDLE     *found;
429         POOL_HANDLE     *tmp;
430         /*
431          * Lock the pool and be fast other thread maybe
432          * waiting for us to finish
433          */
434         MUTEX_LOCK(&inst->perl_pool->mutex);
435
436         found = NULL;
437
438         for (handle = inst->perl_pool->head; handle ; handle = tmp) {
439                 tmp = handle->next;
440
441                 if (handle->status == idle){
442                         found = handle;
443                         break;
444                 }
445         }
446
447         if (found == NULL) {
448                 if (inst->perl_pool->current_clones < inst->perl_pool->max_clones ) {
449
450                         found = pool_grow(inst);
451
452                         if (found == NULL) {
453                                 radlog(L_ERR,"Cannot grow pool returning");
454                                 MUTEX_UNLOCK(&inst->perl_pool->mutex);
455                                 return NULL;
456                         }
457                 } else {
458                         radlog(L_ERR,"rlm_perl:: reached maximum clones %d cannot grow",
459                                         inst->perl_pool->current_clones);
460                         MUTEX_UNLOCK(&inst->perl_pool->mutex);
461                         return NULL;
462                 }
463         }
464
465         move2tail(found, inst);
466         found->status = busy;
467         MUTEX_LOCK(&found->lock);
468         inst->perl_pool->active_clones++;
469         found->request_count++;
470         /*
471          * Hurry Up
472          */
473         MUTEX_UNLOCK(&inst->perl_pool->mutex);
474         radlog(L_DBG,"perl_pool: item 0x%lx asigned new request. Handled so far: %d",
475                         (unsigned long) found->clone, found->request_count);
476         return found;
477 }
478 static int pool_release(POOL_HANDLE *handle, PERL_INST *inst) {
479
480         POOL_HANDLE *tmp, *tmp2;
481         int spare, i, t;
482         time_t  now;
483         /*
484          * Lock it
485          */
486         MUTEX_LOCK(&inst->perl_pool->mutex);
487
488         /*
489          * If detach is set then just release the mutex
490          */
491         if (inst->perl_pool->detach == yes ) {
492         handle->status = idle;
493                 MUTEX_UNLOCK(&handle->lock);
494                 MUTEX_UNLOCK(&inst->perl_pool->mutex);
495                 return 0;
496         }
497
498         MUTEX_UNLOCK(&handle->lock);
499         handle->status = idle;
500         inst->perl_pool->active_clones--;
501
502         spare = inst->perl_pool->current_clones - inst->perl_pool->active_clones;
503
504         radlog(L_DBG,"perl_pool total/active/spare [%d/%d/%d]"
505                         , inst->perl_pool->current_clones, inst->perl_pool->active_clones, spare);
506
507         if (spare < inst->perl_pool->min_spare_clones) {
508                 t = inst->perl_pool->min_spare_clones - spare;
509                 for (i=0;i<t; i++) {
510                         if ((tmp = pool_grow(inst)) == NULL) {
511                                 MUTEX_UNLOCK(&inst->perl_pool->mutex);
512                                 return -1;
513                         }
514                 }
515                 MUTEX_UNLOCK(&inst->perl_pool->mutex);
516                 return 0;
517         }
518         now = time(NULL);
519         if ((now - inst->perl_pool->time_when_last_added) < inst->perl_pool->cleanup_delay) {
520                 MUTEX_UNLOCK(&inst->perl_pool->mutex);
521                 return 0;
522         }
523         if (spare > inst->perl_pool->max_spare_clones) {
524                 spare -= inst->perl_pool->max_spare_clones;
525                 for (tmp = inst->perl_pool->head; (tmp !=NULL ) && (spare > 0) ; tmp = tmp2) {
526                         tmp2 = tmp->next;
527
528                         if(tmp->status == idle) {
529                                 rlm_destroy_perl(tmp->clone);
530                                 delete_pool_handle(tmp,inst);
531                                 spare--;
532                                 break;
533                         }
534                 }
535         }
536         /*
537          * If the clone have reached max_request_per_clone clean it.
538          */
539         if (inst->perl_pool->max_request_per_clone > 0 ) {
540                         if (handle->request_count > inst->perl_pool->max_request_per_clone) {
541                                 rlm_destroy_perl(handle->clone);
542                                 delete_pool_handle(handle,inst);
543                 }
544         }
545         /*
546          * Hurry Up :)
547          */
548         MUTEX_UNLOCK(&inst->perl_pool->mutex);
549         return 0;
550 }
551 static int init_pool (CONF_SECTION *conf, PERL_INST *inst) {
552         POOL_HANDLE     *handle;
553         int t;
554         PERL_POOL       *pool;
555
556
557         pool = rad_malloc(sizeof(PERL_POOL));
558         memset(pool,0,sizeof(PERL_POOL));
559
560         inst->perl_pool = pool;
561
562         MUTEX_INIT(&pool->mutex);
563
564         /*
565          * Read The Config
566          *
567          */
568
569         cf_section_parse(conf,pool,pool_conf);
570         inst->perl_pool = pool;
571         inst->perl_pool->detach = no;
572
573         for(t = 0;t < inst->perl_pool->start_clones ;t++){
574                 if ((handle = pool_grow(inst)) == NULL) {
575                         return -1;
576                 }
577
578         }
579
580         return 1;
581 }
582 #endif
583
584 static void xs_init(pTHX)
585 {
586         char *file = __FILE__;
587
588         /* DynaLoader is a special case */
589         newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
590
591 }
592 /*
593  *
594  * This is wrapper for radlog
595  * Now users can call radiusd::radlog(level,msg) wich is the same
596  * calling radlog from C code.
597  * Boyan
598  */
599 static XS(XS_radiusd_radlog)
600 {
601        dXSARGS;
602        if (items !=2)
603                croak("Usage: radiusd::radlog(level, message)");
604        {
605                int     level;
606                char    *msg;
607
608                level = (int) SvIV(ST(0));
609                msg   = (char *) SvPV(ST(1), PL_na);
610
611                /*
612                 *       Because 'msg' is a 'char *', we don't want '%s', etc.
613                 *       in it to give us printf-style vulnerabilities.
614                 */
615                radlog(level, "rlm_perl: %s", msg);
616         }
617        XSRETURN_NO;
618 }
619
620 /*
621  * The xlat function
622  */
623 static int perl_xlat(void *instance, REQUEST *request, char *fmt, char * out,
624                      size_t freespace, RADIUS_ESCAPE_STRING func)
625 {
626
627         PERL_INST       *inst= (PERL_INST *) instance;
628         PerlInterpreter *perl;
629         char            params[1024], *ptr, *tmp;
630         int             count, ret=0;
631         STRLEN          n_a;
632 #ifndef USE_ITHREADS
633         perl = inst->perl;
634 #endif
635 #ifdef USE_ITHREADS
636         POOL_HANDLE     *handle;
637
638         if ((handle = pool_pop(instance)) == NULL) {
639                 return 0;
640         }
641
642         perl = handle->clone;
643
644         radlog(L_DBG,"Found a interpetator 0x%lx",(unsigned long) perl);
645         {
646         dTHXa(perl);
647         }
648 #endif
649         PERL_SET_CONTEXT(perl);
650         {
651         dSP;
652         ENTER;SAVETMPS;
653
654         /*
655          * Do an xlat on the provided string (nice recursive operation).
656         */
657         if (!radius_xlat(params, sizeof(params), fmt, request, func)) {
658                 radlog(L_ERR, "rlm_perl: xlat failed.");
659                 return 0;
660         }
661         ptr = strtok(params, " ");
662
663         PUSHMARK(SP);
664
665         while (ptr != NULL) {
666                 XPUSHs(sv_2mortal(newSVpv(ptr,0)));
667                 ptr = strtok(NULL, " ");
668         }
669
670         PUTBACK;
671
672         count = call_pv(inst->func_xlat, G_SCALAR | G_EVAL);
673
674         SPAGAIN;
675         if (SvTRUE(ERRSV)) {
676                 radlog(L_ERR, "rlm_perl: perl_xlat exit %s\n",
677                        SvPV(ERRSV,n_a));
678                 return 0;
679         }
680
681         if (count > 0) {
682                 tmp = POPp;
683                 ret = strlen(tmp);
684                 strncpy(out,tmp,ret);
685
686                 radlog(L_DBG,"rlm_perl: Len is %d , out is %s freespace is %d",
687                        ret, out,freespace);
688
689                 PUTBACK ;
690                 FREETMPS ;
691                 LEAVE ;
692
693         }
694         }
695 #ifdef USE_ITHREADS
696         pool_release(handle, instance);
697 #endif
698         return ret;
699 }
700 /*
701  *      Do any per-module initialization that is separate to each
702  *      configured instance of the module.  e.g. set up connections
703  *      to external databases, read configuration files, set up
704  *      dictionary entries, etc.
705  *
706  *      If configuration information is given in the config section
707  *      that must be referenced in later calls, store a handle to it
708  *      in *instance otherwise put a null pointer there.
709  *
710  *      Boyan:
711  *      Setup a hashes wich we will use later
712  *      parse a module and give him a chance to live
713  *
714  */
715 static int perl_instantiate(CONF_SECTION *conf, void **instance)
716 {
717         PERL_INST       *inst = (PERL_INST *) instance;
718         HV              *rad_reply_hv;
719         HV              *rad_check_hv;
720         HV              *rad_request_hv;
721         HV              *rad_request_proxy_hv;
722         HV              *rad_request_proxy_reply_hv;
723         AV              *end_AV;
724
725         char *embed[4];
726         const char *xlat_name;
727         int exitstatus = 0, argc=0;
728
729         /*
730          *      Set up a storage area for instance data
731          */
732         inst = rad_malloc(sizeof(PERL_INST));
733         memset(inst, 0, sizeof(PERL_INST));
734
735         /*
736          *      If the configuration parameters can't be parsed, then
737          *      fail.
738          */
739         if (cf_section_parse(conf, inst, module_config) < 0) {
740                 free(inst);
741                 return -1;
742         }
743
744
745         embed[0] = NULL;
746         if (inst->perl_flags) {
747                 embed[1] = inst->perl_flags;
748                 embed[2] = inst->module;
749                 embed[3] = "0";
750                 argc = 4;
751         } else {
752                 embed[1] = inst->module;
753                 embed[2] = "0";
754                 argc = 3;
755         }
756
757 #ifdef USE_ITHREADS
758         inst->perl = interp;
759         
760         if ((inst->perl = perl_alloc()) == NULL) {
761                 radlog(L_DBG, "rlm_perl: No memory for allocating new perl !");
762                 return (-1);
763         }
764                 
765         perl_construct(inst->perl);
766         PL_perl_destruct_level = 2;
767
768         {
769         dTHXa(inst->perl);
770         }
771         PERL_SET_CONTEXT(inst->perl);
772 #else
773         if ((inst->perl = perl_alloc()) == NULL) {
774                 radlog(L_ERR, "rlm_perl: No memory for allocating new perl !");
775                 return -1;
776         }
777
778         perl_construct(inst->perl);
779 #endif
780
781 #if PERL_REVISION >= 5 && PERL_VERSION >=8
782         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
783 #endif
784
785         exitstatus = perl_parse(inst->perl, xs_init, argc, embed, NULL);
786
787         end_AV = PL_endav;
788         PL_endav = Nullav;
789
790         if(!exitstatus) {
791                 exitstatus = perl_run(inst->perl);
792         } else {
793                 radlog(L_ERR,"rlm_perl: perl_parse failed: %s not found or has syntax errors. \n", inst->module);
794                 return (-1);
795         }
796
797         PL_endav = end_AV;
798
799         newXS("radiusd::radlog",XS_radiusd_radlog, "rlm_perl.c");
800
801         rad_reply_hv = newHV();
802         rad_check_hv = newHV();
803         rad_request_hv = newHV();
804         rad_request_proxy_hv = newHV();
805         rad_request_proxy_reply_hv = newHV();
806
807         rad_reply_hv = get_hv("RAD_REPLY",1);
808         rad_check_hv = get_hv("RAD_CHECK",1);
809         rad_request_hv = get_hv("RAD_REQUEST",1);
810         rad_request_proxy_hv = get_hv("RAD_REQUEST_PROXY",1);
811         rad_request_proxy_reply_hv = get_hv("RAD_REQUEST_PROXY_REPLY",1);
812
813         xlat_name = cf_section_name2(conf);
814         if (xlat_name == NULL)
815                 xlat_name = cf_section_name1(conf);
816         if (xlat_name){
817                 inst->xlat_name = strdup(xlat_name);
818                 xlat_register(xlat_name, perl_xlat, inst);
819         }
820
821 #ifdef USE_ITHREADS
822         if ((init_pool(conf, inst)) == -1) {
823                 radlog(L_ERR,"Couldn't init a pool of perl clones. Exiting");
824                 return -1;
825         }
826
827 #endif
828         *instance = inst;
829
830         return 0;
831 }
832
833 /*
834  *      get the vps and put them in perl hash
835  *      If one VP have multiple values it is added as array_ref
836  *      Example for this is Cisco-AVPair that holds multiple values.
837  *      Which will be available as array_ref in $RAD_REQUEST{'Cisco-AVPair'}
838  */
839 static void perl_store_vps(VALUE_PAIR *vp, HV *rad_hv)
840 {
841         VALUE_PAIR      *nvp, *vpa, *vpn;
842         AV              *av;
843         char            buffer[1024];
844         int             attr, len;
845
846         hv_undef(rad_hv);
847         nvp = paircopy(vp);
848
849         while (nvp != NULL) {
850                 attr = nvp->attribute;
851                 vpa = paircopy2(nvp,attr);
852                 if (vpa->next) {
853                         av = newAV();
854                         vpn = vpa;
855                         while (vpn) {
856                                 len = vp_prints_value(buffer, sizeof(buffer),
857                                                 vpn, FALSE);
858                                 av_push(av, newSVpv(buffer, len));
859                                 vpn = vpn->next;
860                         }
861                         hv_store(rad_hv, nvp->name, strlen(nvp->name),
862                                         newRV_noinc((SV *) av), 0);
863                 } else {
864                         len = vp_prints_value(buffer, sizeof(buffer),
865                                         vpa, FALSE);
866                         hv_store(rad_hv, vpa->name, strlen(vpa->name),
867                                         newSVpv(buffer, len), 0);
868                 }
869
870                 pairfree(&vpa);
871                 vpa = nvp; while ((vpa != NULL) && (vpa->attribute == attr))
872                         vpa = vpa->next;
873                 pairdelete(&nvp, attr);
874                 nvp = vpa;
875         }
876 }
877
878 /*
879  *
880  *     Verify that a Perl SV is a string and save it in FreeRadius
881  *     Value Pair Format
882  *
883  */
884 static int pairadd_sv(VALUE_PAIR **vp, char *key, SV *sv, int operator) {
885        char            *val;
886        VALUE_PAIR      *vpp;
887
888        if (SvOK(sv)) {
889                val = SvPV_nolen(sv);
890                vpp = pairmake(key, val, operator);
891                if (vpp != NULL) {
892                        pairadd(vp, vpp);
893                        radlog(L_DBG,
894                          "rlm_perl: Added pair %s = %s", key, val);
895                        return 1;
896                } else {
897                        radlog(L_DBG,
898                          "rlm_perl: ERROR: Failed to create pair %s = %s",
899                          key, val);
900                }
901         }
902        return 0;
903 }
904
905 /*
906   *     Boyan :
907   *     Gets the content from hashes
908   */
909 static int get_hv_content(HV *my_hv, VALUE_PAIR **vp)
910 {
911        SV               *res_sv, **av_sv;
912        AV               *av;
913        char             *key;
914        I32              key_len, len, i, j;
915        int              ret=0;
916
917        for (i = hv_iterinit(my_hv); i > 0; i--) {
918                res_sv = hv_iternextsv(my_hv,&key,&key_len);
919                if (SvROK(res_sv) && (SvTYPE(SvRV(res_sv)) == SVt_PVAV)) {
920                        av = (AV*)SvRV(res_sv);
921                        len = av_len(av);
922                        for (j = 0; j <= len; j++) {
923                                av_sv = av_fetch(av, j, 0);
924                                ret = pairadd_sv(vp, key, *av_sv, T_OP_ADD) + ret;
925                        }
926                } else ret = pairadd_sv(vp, key, res_sv, T_OP_EQ) + ret;
927         }
928
929         return ret;
930 }
931
932 /*
933  *      Call the function_name inside the module
934  *      Store all vps in hashes %RAD_CHECK %RAD_REPLY %RAD_REQUEST
935  *
936  */
937 static int rlmperl_call(void *instance, REQUEST *request, char *function_name)
938 {
939
940         PERL_INST       *inst = instance;
941         VALUE_PAIR      *vp;
942         int             exitstatus=0, count;
943         STRLEN          n_a;
944
945         HV              *rad_reply_hv;
946         HV              *rad_check_hv;
947         HV              *rad_request_hv;
948         HV              *rad_request_proxy_hv;
949         HV              *rad_request_proxy_reply_hv;
950
951 #ifdef USE_ITHREADS
952         POOL_HANDLE     *handle;
953
954         if ((handle = pool_pop(instance)) == NULL) {
955                 return RLM_MODULE_FAIL;
956         }
957
958         radlog(L_DBG,"found interpetator at address 0x%lx",(unsigned long) handle->clone);
959         {
960         dTHXa(handle->clone);
961         PERL_SET_CONTEXT(handle->clone);
962         }
963 #else
964         PERL_SET_CONTEXT(inst->perl);
965         radlog(L_DBG,"Using perl at 0x%lx",(unsigned long) inst->perl);
966 #endif
967         {
968         dSP;
969
970         ENTER;
971         SAVETMPS;
972
973
974         /*
975          *      Radius has told us to call this function, but none
976          *      is defined.
977          */
978         if (!function_name) {
979                 return RLM_MODULE_FAIL;
980         }
981
982         rad_reply_hv = get_hv("RAD_REPLY",1);
983         rad_check_hv = get_hv("RAD_CHECK",1);
984         rad_request_hv = get_hv("RAD_REQUEST",1);
985         rad_request_proxy_hv = get_hv("RAD_REQUEST_PROXY",1);
986         rad_request_proxy_reply_hv = get_hv("RAD_REQUEST_PROXY_REPLY",1);
987
988
989         perl_store_vps(request->reply->vps, rad_reply_hv);
990         perl_store_vps(request->config_items, rad_check_hv);
991         perl_store_vps(request->packet->vps, rad_request_hv);
992         
993         if (request->proxy != NULL) {
994                 perl_store_vps(request->proxy->vps, rad_request_proxy_hv);
995         } else {
996                 hv_undef(rad_request_proxy_hv);
997         }
998
999         if (request->proxy_reply !=NULL) {
1000                 perl_store_vps(request->proxy_reply->vps, rad_request_proxy_reply_hv);
1001         } else {
1002                 hv_undef(rad_request_proxy_reply_hv);
1003         }       
1004         
1005         vp = NULL;
1006
1007
1008         PUSHMARK(SP);
1009         /*
1010         * This way %RAD_xx can be pushed onto stack as sub parameters.
1011         * XPUSHs( newRV_noinc((SV *)rad_request_hv) );
1012         * XPUSHs( newRV_noinc((SV *)rad_reply_hv) );
1013         * XPUSHs( newRV_noinc((SV *)rad_check_hv) );
1014         * PUTBACK;
1015         */
1016
1017         count = call_pv(function_name, G_SCALAR | G_EVAL | G_NOARGS);
1018
1019         SPAGAIN;
1020
1021         if (count == 1) {
1022                 exitstatus = POPi;
1023                 if (exitstatus >= 100 || exitstatus < 0) {
1024                         exitstatus = RLM_MODULE_FAIL;
1025                 }
1026         }
1027
1028         PUTBACK;
1029         FREETMPS;
1030         LEAVE;
1031
1032         if (SvTRUE(ERRSV)) {
1033                 radlog(L_ERR, "rlm_perl: perl_embed:: module = %s , func = %s exit status= %s\n",
1034                        inst->module,
1035                        function_name, SvPV(ERRSV,n_a));
1036         }
1037
1038         if ((get_hv_content(rad_reply_hv, &vp)) > 0 ) {
1039                 pairmove(&request->reply->vps, &vp);
1040                 pairfree(&vp);
1041         }
1042
1043         if ((get_hv_content(rad_check_hv, &vp)) > 0 ) {
1044                 pairmove(&request->config_items, &vp);
1045                 pairfree(&vp);
1046         }
1047         
1048         if ((get_hv_content(rad_request_proxy_reply_hv, &vp)) > 0 && request->proxy_reply != NULL) {
1049                 pairfree(&request->proxy_reply->vps);
1050                 pairmove(&request->proxy_reply->vps, &vp);
1051                 pairfree(&vp);
1052         }
1053         }
1054 #ifdef USE_ITHREADS
1055         pool_release(handle,instance);
1056         radlog(L_DBG,"Unreserve perl at address 0x%lx", (unsigned long) handle->clone);
1057 #endif
1058
1059         return exitstatus;
1060 }
1061
1062 /*
1063  *      Find the named user in this modules database.  Create the set
1064  *      of attribute-value pairs to check and reply with for this user
1065  *      from the database. The authentication code only needs to check
1066  *      the password, the rest is done here.
1067  */
1068 static int perl_authorize(void *instance, REQUEST *request)
1069 {
1070         return rlmperl_call(instance, request,
1071                             ((PERL_INST *)instance)->func_authorize);
1072 }
1073
1074 /*
1075  *      Authenticate the user with the given password.
1076  */
1077 static int perl_authenticate(void *instance, REQUEST *request)
1078 {
1079         return rlmperl_call(instance, request,
1080                             ((PERL_INST *)instance)->func_authenticate);
1081 }
1082 /*
1083  *      Massage the request before recording it or proxying it
1084  */
1085 static int perl_preacct(void *instance, REQUEST *request)
1086 {
1087         return rlmperl_call(instance, request,
1088                             ((PERL_INST *)instance)->func_preacct);
1089 }
1090 /*
1091  *      Write accounting information to this modules database.
1092  */
1093 static int perl_accounting(void *instance, REQUEST *request)
1094 {
1095         VALUE_PAIR      *pair;
1096         int             acctstatustype=0;
1097
1098         if ((pair = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE)) != NULL) {
1099                 acctstatustype = pair->lvalue;
1100         } else {
1101                 radlog(L_ERR, "Invalid Accounting Packet");
1102                 return RLM_MODULE_INVALID;
1103         }
1104
1105         switch (acctstatustype) {
1106
1107                 case PW_STATUS_START:
1108
1109                         if (((PERL_INST *)instance)->func_start_accounting) {
1110                                 return rlmperl_call(instance, request,
1111                                             ((PERL_INST *)instance)->func_start_accounting);
1112                         } else {
1113                                 return rlmperl_call(instance, request,
1114                                             ((PERL_INST *)instance)->func_accounting);
1115                         }
1116                         break;
1117
1118                 case PW_STATUS_STOP:
1119
1120                         if (((PERL_INST *)instance)->func_stop_accounting) {
1121                                 return rlmperl_call(instance, request,
1122                                             ((PERL_INST *)instance)->func_stop_accounting);
1123                         } else {
1124                                 return rlmperl_call(instance, request,
1125                                             ((PERL_INST *)instance)->func_accounting);
1126                         }
1127                         break;
1128                 default:
1129                         return rlmperl_call(instance, request,
1130                                             ((PERL_INST *)instance)->func_accounting);
1131
1132         }
1133 }
1134 /*
1135  *      Check for simultaneouse-use
1136  */
1137 static int perl_checksimul(void *instance, REQUEST *request)
1138 {
1139         return rlmperl_call(instance, request,
1140                         ((PERL_INST *)instance)->func_checksimul);
1141 }
1142 /*
1143  *      Pre-Proxy request
1144  */
1145 static int perl_pre_proxy(void *instance, REQUEST *request)
1146 {
1147         return rlmperl_call(instance, request,
1148                         ((PERL_INST *)instance)->func_pre_proxy);
1149 }
1150 /*
1151  *      Post-Proxy request
1152  */
1153 static int perl_post_proxy(void *instance, REQUEST *request)
1154 {
1155         return rlmperl_call(instance, request,
1156                         ((PERL_INST *)instance)->func_post_proxy);
1157 }
1158 /*
1159  *      Pre-Auth request
1160  */
1161 static int perl_post_auth(void *instance, REQUEST *request)
1162 {
1163         return rlmperl_call(instance, request,
1164                         ((PERL_INST *)instance)->func_post_auth);
1165 }
1166 /*
1167  * Detach a instance give a chance to a module to make some internal setup ...
1168  */
1169 static int perl_detach(void *instance)
1170 {
1171         PERL_INST       *inst = (PERL_INST *) instance;
1172         int             exitstatus = 0, count = 0;
1173
1174 #ifdef USE_ITHREADS
1175         POOL_HANDLE     *handle, *tmp, *tmp2;
1176
1177         MUTEX_LOCK(&inst->perl_pool->mutex);
1178         inst->perl_pool->detach = yes;
1179         MUTEX_UNLOCK(&inst->perl_pool->mutex);
1180
1181         for (handle = inst->perl_pool->head; handle != NULL; handle = handle->next) {
1182
1183                 radlog(L_DBG,"Detach perl 0x%lx", (unsigned long) handle->clone);
1184                 /*
1185                  * Wait until clone becomes idle
1186                  */
1187                 MUTEX_LOCK(&handle->lock);
1188
1189                 /*
1190                  * Give a clones chance to run detach function
1191                  */
1192                 {
1193                 dTHXa(handle->clone);
1194                 PERL_SET_CONTEXT(handle->clone);
1195                 {
1196                 dSP; ENTER; SAVETMPS; PUSHMARK(SP);
1197                 count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1198                 SPAGAIN;
1199
1200                 if (count == 1) {
1201                         exitstatus = POPi;
1202                         /*
1203                          * FIXME: bug in perl
1204                          *
1205                          */
1206                         if (exitstatus >= 100 || exitstatus < 0) {
1207                                 exitstatus = RLM_MODULE_FAIL;
1208                         }
1209                 }
1210                 PUTBACK;
1211                 FREETMPS;
1212                 LEAVE;
1213                 radlog(L_DBG,"detach at 0x%lx returned status %d",
1214                                 (unsigned long) handle->clone, exitstatus);
1215                 }
1216                 }
1217                 MUTEX_UNLOCK(&handle->lock);
1218         }
1219         /*
1220          * Free handles
1221          */
1222
1223         for (tmp = inst->perl_pool->head; tmp !=NULL  ; tmp = tmp2) {
1224                 tmp2 = tmp->next;
1225                 radlog(L_DBG,"rlm_perl:: Destroy perl");
1226                 rlm_perl_destruct(tmp->clone);
1227                 delete_pool_handle(tmp,inst);
1228         }
1229
1230         {
1231         dTHXa(inst->perl);
1232 #endif /* USE_ITHREADS */
1233         PERL_SET_CONTEXT(inst->perl);
1234         {
1235         dSP; ENTER; SAVETMPS;
1236         PUSHMARK(SP);
1237
1238         count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1239         SPAGAIN;
1240
1241         if (count == 1) {
1242                 exitstatus = POPi;
1243                 if (exitstatus >= 100 || exitstatus < 0) {
1244                         exitstatus = RLM_MODULE_FAIL;
1245                 }
1246         }
1247         PUTBACK;
1248         FREETMPS;
1249         LEAVE;
1250         }
1251 #ifdef USE_ITHREADS
1252         }
1253 #endif
1254
1255         xlat_unregister(inst->xlat_name, perl_xlat);
1256         free(inst->xlat_name);
1257
1258         if (inst->func_authorize) free(inst->func_authorize);
1259         if (inst->func_authenticate) free(inst->func_authenticate);
1260         if (inst->func_accounting) free(inst->func_accounting);
1261         if (inst->func_preacct) free(inst->func_preacct);
1262         if (inst->func_checksimul) free(inst->func_checksimul);
1263         if (inst->func_pre_proxy) free(inst->func_pre_proxy);
1264         if (inst->func_post_proxy) free(inst->func_post_proxy);
1265         if (inst->func_post_auth) free(inst->func_post_auth);
1266         if (inst->func_detach) free(inst->func_detach);
1267
1268 #ifdef USE_ITHREADS
1269         free(inst->perl_pool->head);
1270         free(inst->perl_pool->tail);
1271         MUTEX_DESTROY(&inst->perl_pool->mutex);
1272         free(inst->perl_pool);
1273         rlm_perl_destruct(inst->perl);
1274 #else
1275         perl_destruct(inst->perl);
1276         perl_free(inst->perl);
1277 #endif
1278
1279         free(inst);
1280         return exitstatus;
1281 }
1282 /*
1283  *      The module name should be the only globally exported symbol.
1284  *      That is, everything else should be 'static'.
1285  *
1286  *      If the module needs to temporarily modify it's instantiation
1287  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
1288  *      The server will then take care of ensuring that the module
1289  *      is single-threaded.
1290  */
1291 module_t rlm_perl = {
1292         RLM_MODULE_INIT,
1293         "perl",                         /* Name */
1294 #ifdef USE_ITHREADS
1295         RLM_TYPE_THREAD_SAFE,           /* type */
1296 #else
1297         RLM_TYPE_THREAD_UNSAFE,
1298 #endif
1299         perl_instantiate,               /* instantiation */
1300         perl_detach,                    /* detach */
1301         {
1302                 perl_authenticate,      /* authenticate */
1303                 perl_authorize,         /* authorize */
1304                 perl_preacct,           /* preacct */
1305                 perl_accounting,        /* accounting */
1306                 perl_checksimul,        /* check simul */
1307                 perl_pre_proxy,         /* pre-proxy */
1308                 perl_post_proxy,        /* post-proxy */
1309                 perl_post_auth          /* post-auth */
1310         },
1311 };