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