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