Latest set of changes
[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 #ifdef USE_ITHREADS
596         if ((interp = perl_alloc()) == NULL) {
597                 radlog(L_DBG, "rlm_perl: No memory for allocating new perl !");
598                 return -1;
599         }
600
601         perl_construct(interp);
602         PL_perl_destruct_level = 2;
603 #endif
604         return 0;
605
606 }
607
608 static void xs_init(pTHX)
609 {
610         char *file = __FILE__;
611
612         /* DynaLoader is a special case */
613         newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
614
615 }
616 /*
617  *
618  * This is wrapper for radlog
619  * Now users can call radiusd::radlog(level,msg) wich is the same
620  * calling radlog from C code.
621  * Boyan
622  */
623 static XS(XS_radiusd_radlog)
624 {
625        dXSARGS;
626        if (items !=2)
627                croak("Usage: radiusd::radlog(level, message)");
628        {
629                int     level;
630                char    *msg;
631
632                level = (int) SvIV(ST(0));
633                msg   = (char *) SvPV(ST(1), PL_na);
634
635                /*
636                 *       Because 'msg' is a 'char *', we don't want '%s', etc.
637                 *       in it to give us printf-style vulnerabilities.
638                 */
639                radlog(level, "rlm_perl: %s", msg);
640         }
641        XSRETURN_NO;
642 }
643
644 /*
645  * The xlat function
646  */
647 static int perl_xlat(void *instance, REQUEST *request, char *fmt, char * out,
648                      size_t freespace, RADIUS_ESCAPE_STRING func)
649 {
650
651         PERL_INST       *inst= (PERL_INST *) instance;
652         PerlInterpreter *perl;
653         char            params[1024], *ptr, *tmp;
654         int             count, ret=0;
655         STRLEN          n_a;
656 #ifndef USE_ITHREADS
657         perl = inst->perl;
658 #endif
659 #ifdef USE_ITHREADS
660         POOL_HANDLE     *handle;
661
662         if ((handle = pool_pop(instance)) == NULL) {
663                 return 0;
664         }
665
666         perl = handle->clone;
667
668         radlog(L_DBG,"Found a interpetator 0x%lx",(unsigned long) perl);
669         {
670         dTHXa(perl);
671         }
672 #endif
673         PERL_SET_CONTEXT(perl);
674         {
675         dSP;
676         ENTER;SAVETMPS;
677
678         /*
679          * Do an xlat on the provided string (nice recursive operation).
680         */
681         if (!radius_xlat(params, sizeof(params), fmt, request, func)) {
682                 radlog(L_ERR, "rlm_perl: xlat failed.");
683                 return 0;
684         }
685         ptr = strtok(params, " ");
686
687         PUSHMARK(SP);
688
689         while (ptr != NULL) {
690                 XPUSHs(sv_2mortal(newSVpv(ptr,0)));
691                 ptr = strtok(NULL, " ");
692         }
693
694         PUTBACK;
695
696         count = call_pv(inst->func_xlat, G_SCALAR | G_EVAL);
697
698         SPAGAIN;
699         if (SvTRUE(ERRSV)) {
700                 radlog(L_ERR, "rlm_perl: perl_xlat exit %s\n",
701                        SvPV(ERRSV,n_a));
702                 return 0;
703         }
704
705         if (count > 0) {
706                 tmp = POPp;
707                 ret = strlen(tmp);
708                 strncpy(out,tmp,ret);
709
710                 radlog(L_DBG,"rlm_perl: Len is %d , out is %s freespace is %d",
711                        ret, out,freespace);
712
713                 PUTBACK ;
714                 FREETMPS ;
715                 LEAVE ;
716
717         }
718         }
719 #ifdef USE_ITHREADS
720         pool_release(handle, instance);
721 #endif
722         return ret;
723 }
724 /*
725  *      Do any per-module initialization that is separate to each
726  *      configured instance of the module.  e.g. set up connections
727  *      to external databases, read configuration files, set up
728  *      dictionary entries, etc.
729  *
730  *      If configuration information is given in the config section
731  *      that must be referenced in later calls, store a handle to it
732  *      in *instance otherwise put a null pointer there.
733  *
734  *      Boyan:
735  *      Setup a hashes wich we will use later
736  *      parse a module and give him a chance to live
737  *
738  */
739 static int perl_instantiate(CONF_SECTION *conf, void **instance)
740 {
741         PERL_INST       *inst = (PERL_INST *) instance;
742         HV              *rad_reply_hv;
743         HV              *rad_check_hv;
744         HV              *rad_request_hv;
745         HV              *rad_request_proxy_hv;
746         HV              *rad_request_proxy_reply_hv;
747         AV              *end_AV;
748
749         char *embed[4], *xlat_name;
750         int exitstatus = 0, argc=0;
751
752         /*
753          *      Set up a storage area for instance data
754          */
755         inst = rad_malloc(sizeof(PERL_INST));
756         memset(inst, 0, sizeof(PERL_INST));
757
758         /*
759          *      If the configuration parameters can't be parsed, then
760          *      fail.
761          */
762         if (cf_section_parse(conf, inst, module_config) < 0) {
763                 free(inst);
764                 return -1;
765         }
766
767
768         embed[0] = NULL;
769         if (inst->perl_flags) {
770                 embed[1] = inst->perl_flags;
771                 embed[2] = inst->module;
772                 embed[3] = "0";
773                 argc = 4;
774         } else {
775                 embed[1] = inst->module;
776                 embed[2] = "0";
777                 argc = 3;
778         }
779
780 #ifdef USE_ITHREADS
781         inst->perl = interp;
782         {
783         dTHXa(inst->perl);
784         }
785         PERL_SET_CONTEXT(inst->perl);
786 #else
787         if ((inst->perl = perl_alloc()) == NULL) {
788                 radlog(L_ERR, "rlm_perl: No memory for allocating new perl !");
789                 return -1;
790         }
791
792         perl_construct(inst->perl);
793 #endif
794
795 #if PERL_REVISION >= 5 && PERL_VERSION >=8
796         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
797 #endif
798
799         exitstatus = perl_parse(inst->perl, xs_init, argc, embed, NULL);
800
801         end_AV = PL_endav;
802         PL_endav = Nullav;
803
804         if(!exitstatus) {
805                 exitstatus = perl_run(inst->perl);
806         } else {
807                 radlog(L_ERR,"rlm_perl: perl_parse failed: %s not found or has syntax errors. \n", inst->module);
808                 return (-1);
809         }
810
811         PL_endav = end_AV;
812
813         newXS("radiusd::radlog",XS_radiusd_radlog, "rlm_perl.c");
814
815         rad_reply_hv = newHV();
816         rad_check_hv = newHV();
817         rad_request_hv = newHV();
818         rad_request_proxy_hv = newHV();
819         rad_request_proxy_reply_hv = newHV();
820
821         rad_reply_hv = get_hv("RAD_REPLY",1);
822         rad_check_hv = get_hv("RAD_CHECK",1);
823         rad_request_hv = get_hv("RAD_REQUEST",1);
824         rad_request_proxy_hv = get_hv("RAD_REQUEST_PROXY",1);
825         rad_request_proxy_reply_hv = get_hv("RAD_REQUEST_PROXY_REPLY",1);
826
827         xlat_name = cf_section_name2(conf);
828         if (xlat_name == NULL)
829                 xlat_name = cf_section_name1(conf);
830         if (xlat_name){
831                 inst->xlat_name = strdup(xlat_name);
832                 xlat_register(xlat_name, perl_xlat, inst);
833         }
834
835 #ifdef USE_ITHREADS
836         if ((init_pool(conf, inst)) == -1) {
837                 radlog(L_ERR,"Couldn't init a pool of perl clones. Exiting");
838                 return -1;
839         }
840
841 #endif
842         *instance = inst;
843
844         return 0;
845 }
846
847 /*
848  *      get the vps and put them in perl hash
849  *      If one VP have multiple values it is added as array_ref
850  *      Example for this is Cisco-AVPair that holds multiple values.
851  *      Which will be available as array_ref in $RAD_REQUEST{'Cisco-AVPair'}
852  */
853 static void perl_store_vps(VALUE_PAIR *vp, HV *rad_hv)
854 {
855         VALUE_PAIR      *nvp, *vpa, *vpn;
856         AV              *av;
857         char            buffer[1024];
858         int             attr, len;
859
860         hv_undef(rad_hv);
861         nvp = paircopy(vp);
862
863         while (nvp != NULL) {
864                 attr = nvp->attribute;
865                 vpa = paircopy2(nvp,attr);
866                 if (vpa->next) {
867                         av = newAV();
868                         vpn = vpa;
869                         while (vpn) {
870                                 len = vp_prints_value(buffer, sizeof(buffer),
871                                                 vpn, FALSE);
872                                 av_push(av, newSVpv(buffer, len));
873                                 vpn = vpn->next;
874                         }
875                         hv_store(rad_hv, nvp->name, strlen(nvp->name),
876                                         newRV_noinc((SV *) av), 0);
877                 } else {
878                         len = vp_prints_value(buffer, sizeof(buffer),
879                                         vpa, FALSE);
880                         hv_store(rad_hv, vpa->name, strlen(vpa->name),
881                                         newSVpv(buffer, len), 0);
882                 }
883
884                 pairfree(&vpa);
885                 vpa = nvp; while ((vpa != NULL) && (vpa->attribute == attr))
886                         vpa = vpa->next;
887                 pairdelete(&nvp, attr);
888                 nvp = vpa;
889         }
890 }
891
892 /*
893  *
894  *     Verify that a Perl SV is a string and save it in FreeRadius
895  *     Value Pair Format
896  *
897  */
898 static int pairadd_sv(VALUE_PAIR **vp, char *key, SV *sv) {
899        char            *val;
900        VALUE_PAIR      *vpp;
901
902        if (SvOK(sv)) {
903                val = SvPV_nolen(sv);
904                vpp = pairmake(key, val, T_OP_EQ);
905                if (vpp != NULL) {
906                        pairadd(vp, vpp);
907                        radlog(L_DBG,
908                          "rlm_perl: Added pair %s = %s", key, val);
909                        return 1;
910                } else {
911                        radlog(L_DBG,
912                          "rlm_perl: ERROR: Failed to create pair %s = %s",
913                          key, val);
914                }
915         }
916        return 0;
917 }
918
919 /*
920   *     Boyan :
921   *     Gets the content from hashes
922   */
923 static int get_hv_content(HV *my_hv, VALUE_PAIR **vp)
924 {
925        SV               *res_sv, **av_sv;
926        AV               *av;
927        char             *key;
928        I32              key_len, len, i, j;
929        int              ret=0;
930
931        for (i = hv_iterinit(my_hv); i > 0; i--) {
932                res_sv = hv_iternextsv(my_hv,&key,&key_len);
933                if (SvROK(res_sv) && (SvTYPE(SvRV(res_sv)) == SVt_PVAV)) {
934                        av = (AV*)SvRV(res_sv);
935                        len = av_len(av);
936                        for (j = 0; j <= len; j++) {
937                                av_sv = av_fetch(av, j, 0);
938                                ret = pairadd_sv(vp, key, *av_sv) + ret;
939                        }
940                } else ret = pairadd_sv(vp, key, res_sv) + ret;
941         }
942
943         return ret;
944 }
945
946 /*
947  *      Call the function_name inside the module
948  *      Store all vps in hashes %RAD_CHECK %RAD_REPLY %RAD_REQUEST
949  *
950  */
951 static int rlmperl_call(void *instance, REQUEST *request, char *function_name)
952 {
953
954         PERL_INST       *inst = instance;
955         VALUE_PAIR      *vp;
956         int             exitstatus=0, count;
957         STRLEN          n_a;
958
959         HV              *rad_reply_hv;
960         HV              *rad_check_hv;
961         HV              *rad_request_hv;
962         HV              *rad_request_proxy_hv;
963         HV              *rad_request_proxy_reply_hv;
964
965 #ifdef USE_ITHREADS
966         POOL_HANDLE     *handle;
967
968         if ((handle = pool_pop(instance)) == NULL) {
969                 return RLM_MODULE_FAIL;
970         }
971
972         radlog(L_DBG,"found interpetator at address 0x%lx",(unsigned long) handle->clone);
973         {
974         dTHXa(handle->clone);
975         PERL_SET_CONTEXT(handle->clone);
976         }
977 #else
978         PERL_SET_CONTEXT(inst->perl);
979         radlog(L_DBG,"Using perl at 0x%lx",(unsigned long) inst->perl);
980 #endif
981         {
982         dSP;
983
984         ENTER;
985         SAVETMPS;
986
987
988         /*
989          *      Radius has told us to call this function, but none
990          *      is defined.
991          */
992         if (!function_name) {
993                 return RLM_MODULE_FAIL;
994         }
995
996         rad_reply_hv = get_hv("RAD_REPLY",1);
997         rad_check_hv = get_hv("RAD_CHECK",1);
998         rad_request_hv = get_hv("RAD_REQUEST",1);
999         rad_request_proxy_hv = get_hv("RAD_REQUEST_PROXY",1);
1000         rad_request_proxy_reply_hv = get_hv("RAD_REQUEST_PROXY_REPLY",1);
1001
1002
1003         perl_store_vps(request->reply->vps, rad_reply_hv);
1004         perl_store_vps(request->config_items, rad_check_hv);
1005         perl_store_vps(request->packet->vps, rad_request_hv);
1006         
1007         if (request->proxy != NULL) {
1008                 perl_store_vps(request->proxy->vps, rad_request_proxy_hv);
1009         } else {
1010                 hv_undef(rad_request_proxy_hv);
1011         }
1012
1013         if (request->proxy_reply !=NULL) {
1014                 perl_store_vps(request->proxy_reply->vps, rad_request_proxy_reply_hv);
1015         } else {
1016                 hv_undef(rad_request_proxy_reply_hv);
1017         }       
1018         
1019         vp = NULL;
1020
1021
1022         PUSHMARK(SP);
1023         /*
1024         * This way %RAD_xx can be pushed onto stack as sub parameters.
1025         * XPUSHs( newRV_noinc((SV *)rad_request_hv) );
1026         * XPUSHs( newRV_noinc((SV *)rad_reply_hv) );
1027         * XPUSHs( newRV_noinc((SV *)rad_check_hv) );
1028         * PUTBACK;
1029         */
1030
1031         count = call_pv(function_name, G_SCALAR | G_EVAL | G_NOARGS);
1032
1033         SPAGAIN;
1034
1035         if (count == 1) {
1036                 exitstatus = POPi;
1037                 if (exitstatus >= 100 || exitstatus < 0) {
1038                         exitstatus = RLM_MODULE_FAIL;
1039                 }
1040         }
1041
1042         PUTBACK;
1043         FREETMPS;
1044         LEAVE;
1045
1046         if (SvTRUE(ERRSV)) {
1047                 radlog(L_ERR, "rlm_perl: perl_embed:: module = %s , func = %s exit status= %s\n",
1048                        inst->module,
1049                        function_name, SvPV(ERRSV,n_a));
1050         }
1051
1052         if ((get_hv_content(rad_reply_hv, &vp)) > 0 ) {
1053                 pairmove(&request->reply->vps, &vp);
1054                 pairfree(&vp);
1055         }
1056
1057         if ((get_hv_content(rad_check_hv, &vp)) > 0 ) {
1058                 pairmove(&request->config_items, &vp);
1059                 pairfree(&vp);
1060         }
1061         
1062         if ((get_hv_content(rad_request_proxy_reply_hv, &vp)) > 0 && request->proxy_reply != NULL) {
1063                 pairfree(&request->proxy_reply->vps);
1064                 pairmove(&request->proxy_reply->vps, &vp);
1065                 pairfree(&vp);
1066         }
1067         }
1068 #ifdef USE_ITHREADS
1069         pool_release(handle,instance);
1070         radlog(L_DBG,"Unreserve perl at address 0x%lx", (unsigned long) handle->clone);
1071 #endif
1072
1073         return exitstatus;
1074 }
1075
1076 /*
1077  *      Find the named user in this modules database.  Create the set
1078  *      of attribute-value pairs to check and reply with for this user
1079  *      from the database. The authentication code only needs to check
1080  *      the password, the rest is done here.
1081  */
1082 static int perl_authorize(void *instance, REQUEST *request)
1083 {
1084         return rlmperl_call(instance, request,
1085                             ((PERL_INST *)instance)->func_authorize);
1086 }
1087
1088 /*
1089  *      Authenticate the user with the given password.
1090  */
1091 static int perl_authenticate(void *instance, REQUEST *request)
1092 {
1093         return rlmperl_call(instance, request,
1094                             ((PERL_INST *)instance)->func_authenticate);
1095 }
1096 /*
1097  *      Massage the request before recording it or proxying it
1098  */
1099 static int perl_preacct(void *instance, REQUEST *request)
1100 {
1101         return rlmperl_call(instance, request,
1102                             ((PERL_INST *)instance)->func_preacct);
1103 }
1104 /*
1105  *      Write accounting information to this modules database.
1106  */
1107 static int perl_accounting(void *instance, REQUEST *request)
1108 {
1109         VALUE_PAIR      *pair;
1110         int             acctstatustype=0;
1111
1112         if ((pair = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE)) != NULL) {
1113                 acctstatustype = pair->lvalue;
1114         } else {
1115                 radlog(L_ERR, "Invalid Accounting Packet");
1116                 return RLM_MODULE_INVALID;
1117         }
1118
1119         switch (acctstatustype) {
1120
1121                 case PW_STATUS_START:
1122
1123                         if (((PERL_INST *)instance)->func_start_accounting) {
1124                                 return rlmperl_call(instance, request,
1125                                             ((PERL_INST *)instance)->func_start_accounting);
1126                         } else {
1127                                 return rlmperl_call(instance, request,
1128                                             ((PERL_INST *)instance)->func_accounting);
1129                         }
1130                         break;
1131
1132                 case PW_STATUS_STOP:
1133
1134                         if (((PERL_INST *)instance)->func_stop_accounting) {
1135                                 return rlmperl_call(instance, request,
1136                                             ((PERL_INST *)instance)->func_stop_accounting);
1137                         } else {
1138                                 return rlmperl_call(instance, request,
1139                                             ((PERL_INST *)instance)->func_accounting);
1140                         }
1141                         break;
1142                 default:
1143                         return rlmperl_call(instance, request,
1144                                             ((PERL_INST *)instance)->func_accounting);
1145
1146         }
1147 }
1148 /*
1149  *      Check for simultaneouse-use
1150  */
1151 static int perl_checksimul(void *instance, REQUEST *request)
1152 {
1153         return rlmperl_call(instance, request,
1154                         ((PERL_INST *)instance)->func_checksimul);
1155 }
1156 /*
1157  *      Pre-Proxy request
1158  */
1159 static int perl_pre_proxy(void *instance, REQUEST *request)
1160 {
1161         return rlmperl_call(instance, request,
1162                         ((PERL_INST *)instance)->func_pre_proxy);
1163 }
1164 /*
1165  *      Post-Proxy request
1166  */
1167 static int perl_post_proxy(void *instance, REQUEST *request)
1168 {
1169         return rlmperl_call(instance, request,
1170                         ((PERL_INST *)instance)->func_post_proxy);
1171 }
1172 /*
1173  *      Pre-Auth request
1174  */
1175 static int perl_post_auth(void *instance, REQUEST *request)
1176 {
1177         return rlmperl_call(instance, request,
1178                         ((PERL_INST *)instance)->func_post_auth);
1179 }
1180 /*
1181  * Detach a instance give a chance to a module to make some internal setup ...
1182  */
1183 static int perl_detach(void *instance)
1184 {
1185         PERL_INST       *inst = (PERL_INST *) instance;
1186         int             exitstatus=0,count=0;
1187
1188 #ifdef USE_ITHREADS
1189         POOL_HANDLE     *handle, *tmp, *tmp2;
1190
1191         MUTEX_LOCK(&inst->perl_pool->mutex);
1192         inst->perl_pool->detach = yes;
1193         MUTEX_UNLOCK(&inst->perl_pool->mutex);
1194
1195         for (handle = inst->perl_pool->head; handle != NULL; handle = handle->next) {
1196
1197                 radlog(L_DBG,"Detach perl 0x%lx", (unsigned long) handle->clone);
1198                 /*
1199                  * Wait until clone becomes idle
1200                  */
1201                 MUTEX_LOCK(&handle->lock);
1202
1203                 /*
1204                  * Give a clones chance to run detach function
1205                  */
1206                 {
1207                 dTHXa(handle->clone);
1208                 PERL_SET_CONTEXT(handle->clone);
1209                 {
1210                 dSP; ENTER; SAVETMPS; PUSHMARK(SP);
1211                 count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1212                 SPAGAIN;
1213
1214                 if (count == 1) {
1215                         exitstatus = POPi;
1216                         /*
1217                          * FIXME: bug in perl
1218                          *
1219                          */
1220                         if (exitstatus >= 100 || exitstatus < 0) {
1221                                 exitstatus = RLM_MODULE_FAIL;
1222                         }
1223                 }
1224                 PUTBACK;
1225                 FREETMPS;
1226                 LEAVE;
1227                 radlog(L_DBG,"detach at 0x%lx returned status %d",
1228                                 (unsigned long) handle->clone, exitstatus);
1229                 }
1230                 }
1231                 MUTEX_UNLOCK(&handle->lock);
1232         }
1233         /*
1234          * Free handles
1235          */
1236
1237         for (tmp = inst->perl_pool->head; tmp !=NULL  ; tmp = tmp2) {
1238                 tmp2 = tmp->next;
1239                 radlog(L_DBG,"rlm_perl:: Destroy perl");
1240                 rlm_perl_destruct(tmp->clone);
1241                 delete_pool_handle(tmp,inst);
1242         }
1243
1244         {
1245         dTHXa(inst->perl);
1246 #endif /* USE_ITHREADS */
1247         PERL_SET_CONTEXT(inst->perl);
1248         {
1249         dSP; ENTER; SAVETMPS;
1250         PUSHMARK(SP);
1251
1252         count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1253         SPAGAIN;
1254
1255         if (count == 1) {
1256                 exitstatus = POPi;
1257                 if (exitstatus >= 100 || exitstatus < 0) {
1258                         exitstatus = RLM_MODULE_FAIL;
1259                 }
1260         }
1261         PUTBACK;
1262         FREETMPS;
1263         LEAVE;
1264         }
1265 #ifdef USE_ITHREADS
1266         }
1267 #endif
1268
1269         xlat_unregister(inst->xlat_name, perl_xlat);
1270         free(inst->xlat_name);
1271
1272         if (inst->func_authorize) free(inst->func_authorize);
1273         if (inst->func_authenticate) free(inst->func_authenticate);
1274         if (inst->func_accounting) free(inst->func_accounting);
1275         if (inst->func_preacct) free(inst->func_preacct);
1276         if (inst->func_checksimul) free(inst->func_checksimul);
1277         if (inst->func_pre_proxy) free(inst->func_pre_proxy);
1278         if (inst->func_post_proxy) free(inst->func_post_proxy);
1279         if (inst->func_post_auth) free(inst->func_post_auth);
1280         if (inst->func_detach) free(inst->func_detach);
1281
1282 #ifdef USE_ITHREADS
1283         free(inst->perl_pool->head);
1284         free(inst->perl_pool->tail);
1285         MUTEX_DESTROY(&inst->perl_pool->mutex);
1286         free(inst->perl_pool);
1287         rlm_perl_destruct(inst->perl);
1288 #else
1289         perl_destruct(inst->perl);
1290         perl_free(inst->perl);
1291 #endif
1292
1293         free(inst);
1294         return exitstatus;
1295 }
1296 /*
1297  *      The module name should be the only globally exported symbol.
1298  *      That is, everything else should be 'static'.
1299  *
1300  *      If the module needs to temporarily modify it's instantiation
1301  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
1302  *      The server will then take care of ensuring that the module
1303  *      is single-threaded.
1304  */
1305 module_t rlm_perl = {
1306         "perl",                         /* Name */
1307 #ifdef USE_ITHREADS
1308         RLM_TYPE_THREAD_SAFE,           /* type */
1309 #else
1310         RLM_TYPE_THREAD_UNSAFE,
1311 #endif
1312         perl_init,                      /* initialization */
1313         perl_instantiate,               /* instantiation */
1314         {
1315                 perl_authenticate,
1316                 perl_authorize,
1317                 perl_preacct,
1318                 perl_accounting,
1319                 perl_checksimul,        /* check simul */
1320                 perl_pre_proxy,  /* pre-proxy */
1321                 perl_post_proxy,        /* post-proxy */
1322                 perl_post_auth    /* post-auth */
1323         },
1324         perl_detach,                    /* detach */
1325         NULL,                           /* destroy */
1326 };